jquery: function in "onclick"
$('.more').click(function test(id) {
$('#MoreFriendInfo'+id).toggle();
});
I made this, function test(id), now how should i make the link right in html/php in order to grab the id? I tried this, but it doesnt work:
<a class='more' href="javascript:void(0);" onclick='test(<?php echo $showInfo["bID"]; ?>)'>mer</a>
In firebug i get "test isn开发者_开发百科t defined"
In all of these, we're removing the onclick
from the markup:
You can use a data attribute, like this:
<a class='more' href='#' data-id='<?php echo $showInfo["bID"]; ?>'>mer</a>
Then grab it in your .click()
handler, like this:
$('.more').click(function () {
$('#MoreFriendInfo'+$(this).attr('data-id')).toggle();
});
Alternatively if it's in another container forget the IDs and find it relatively, for example if the markup was like this:
<div class="container">
<a class='more' href="#">mer</a>
<div class="moreFriendInfo">Content</div>
</div>
You could do it like this:
$('.more').click(function () {
$(this).closest('.container').find('.moreFriendInfo').toggle();
});
(In this case you can actually use .siblings()
, but it's meant to be a more general approach)
The way you are defining it, test(id)
is an inner function that is only scoped within .click()
.
Note that when you use .click(), you are effectively defining onclick. You don't need to add it to the markup also.
Rather than passing the id, I would design the markup in such a way that the elements were placed in such a way that I could use selector context to pass a starting point for the selector.
$('.more').click(function () { $('.moreFriendInfo',this).toggle(); });
Nick's answer is almost perfect, but I'd use "rel" instead of "data-id" unless data-id is a valid HTML attribute.
精彩评论