Jquery click function not loading new content

2019-08-30 06:29发布

问题:

For some reason jquery does not load the new html into the #textoPequeno div. It actually removes the old content, that as far as it gets.

Here's the html code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<link href="css/style.css" media="screen" rel="stylesheet" type="text/css">
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
<script type="text/javascript" src="include/javascript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Opera</title>
</head>

<body>
    <div class="main">
        <div id="header">

            <h1 id="logo">
                <a href="#">Linux Logo</a>
            </h1>

            <ul>
                <li><a href="test.html">Home</a></li>
                <li><a href="test">Home</a></li>
                <li><a href="#">Home</a></li>
                <li><a href="#">Home</a></li>
                <li><a href="#">Home</a></li>
            </ul>

            <div id="player"></div>

        </div>
    <div id="imagen"></div>
    <h2 id="textoGrande"><p>Opera ahora<br /> mas acojedor...</p>
    </h2><h3 id="textoPequeno"><p>En su nueva versión, Opera apuesta por un nuevo diseño y pestañas visuales, un motor más veloz que incrementa su velocidad en un 40% frente a su anterior versión y un mejor soporte de estándares.</p>

    </h3></div>


</body></html>

And the jquery code

    $("li a").live("click", function(){
       $("#textoPequeno").load($(this).attr('href')+' .main');    
       return false;
});

Please check the live sample: http://gabrielmeono.com/working/

EDIT:

If I remove the main from the javascript code, the page will not load inside the div. It will remain as it is.

回答1:

Your code is fine, your html is wrong.

It looks like you're trying to create stand alone pages that also has the capabilities of being loaded through ajax.

You are appending ' .main' to your .load() call, which is equivalent to selecting '.main' from the returned content. If you are doing that, all your html pages need to have an element with class='main' in it.

My suggestion would be to use id='main' instead of a class. Then change your call to: $("#textoPequeno").load($(this).attr('href')+' #main');



回答2:

get rid of + ' .main'

$("li a").live("click", function(){
   $("#textoPequeno").load( $(this).attr('href') );    
   return false;
});

is fine as long as there is content at 'href' to load into #textoPequeno



回答3:

rkw's answer is correct. I would add that you could also move the #main to the actual href prop. It may not seem like much, but it will reduce some overhead and in the event your AJAX call fails (Or for a few other reasons) the user is directed to the actual href - they would be sent to the correct spot.