开发者

can't get jQuery .load to load content into div

开发者 https://www.devze.com 2023-01-21 03:00 出处:网络
I have a list as such : <ul id=\"yearMenu\"> <li>Select a year</li> <li><a href=\"AJAX/2010PR.html\">2010</a> |</li>

I have a list as such :

<ul id="yearMenu">
  <li>Select a year</li>
  <li><a href="AJAX/2010PR.html">2010</a> |</li>
  <li><a href="AJAX/2009PR.html">2009</a> |</li>
  <li><a href="AJAX/2008PR.html">2008</a> |</li>
  <li><a href="AJAX/2007PR.html">2007</a> |</li>
  <li><a href="AJAX/200开发者_高级运维6PR.html">2006</a> |</li>
  <li><a href="AJAX/2005PR.html">2005</a></li>
</ul>

below that in another container is this div:

<div id="tableContent" class="tabWrapp"></div>

and the following load function:

$("#ul#yearMenu li a").click(function() {
  var $parent = $(this).parent();
  $parent.addClass("selected").siblings().removeClass("selected");
  var href = $(this).attr('href');
  $("#tableContent").load(href + " #tableContent ", function() {
    //need to do something here?
  });
});

but all links open in another page. what do I need to do to get this to load in the #tableContent div?


Try adding

return false;

to the end of your "click" handler. Without that, the default action of each <a> tag will be taken.

It would be even better (safer, some would say) to call .preventDefault() on the event object:

$('#whatever').click(function(evt) {
  // ...
  evt.preventDefault();
});

That'll allow the event to bubble but prevent the <a> default action.


Try this:

$("ul#yearMenu li a").click(function(event) {
  var $parent = $(this).parent();
  $parent.addClass("selected").siblings().removeClass("selected");
  var href = $(this).attr('href');
  $.get(href, function(data) {
    $('#tableContent').html(data);
  });
  event.preventDefault();
});


Don't use href to store the link. use a custom attr like 'data-link="http://link.com"'

<li><a data-link="AJAX/2010PR.html">2010</a> |</li>

so, when you click nothing will happen.

In your javascript code, you get the link using:

$(selector).attr("data-link");

Then to makeup the A as link, use some css.

It's just a alternative way, but with "preventDefault()" or "return false", also works well.

0

精彩评论

暂无评论...
验证码 换一张
取 消