开发者

Jquery variable problem

开发者 https://www.devze.com 2023-01-08 14:06 出处:网络
The HTML: <div class=\"first\" id=\"first_id\"> <div class=\"second\">text sample</div>

The HTML:

<div class="first" id="first_id">
<div class="second">text sample</div>
<div class="third"><button type="submit" class="some_class" id="some_id">send</button></div>
</div>

Jquery:

$("#some_id").click(function() {
var test = $(this).closest('.first').attr('id');
..
开发者_JS百科return false;
});

I want to replace content of the "first" div using var "test" in jquery code above. Something like:

$("."+test).html('<img src="img/spin.gif">');

But when I put this part of the code in function above it does not work. What I did wrong?


You're getting the ID but selecting it as a .class selector (so it should be $("#"+test)), but it can be easier, like this:

$("#some_id").click(function() {
  $(this).closest('.first').html('<img src="img/spin.gif">');
  return false;
});

There's no need to go selecting the element again, you already have it, so just calling .html() on the element you found with .closest() works, simpler and faster :)


For completeness sake though, what you should do is this:

$("#some_id").click(function() {
  $(this).closest('.first').empty().append('<img src="img/spin.gif">');
  return false;
});

Using a .empty() call will cleanup the click handler we're in, otherwise it'l be left around in $.cache...this isn't a big issue, but if you have lots of elements it adds up, it's best to always cleanup if possible.


You put id value into the test, but then you use '.' in selector. Instead you should use '#'.

0

精彩评论

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