开发者

jquery $this loses track of current tags?

开发者 https://www.devze.com 2023-03-31 05:50 出处:网络
I got this html code from a book that i\'m using to learn jquery i modified it a little bit <body>

I got this html code from a book that i'm using to learn jquery i modified it a little bit

<body>
<h4><i>More</i> Mitch Hedberg Quotes</h4>
<div>
  <input type='submit' id='tmpQuote1' value='View Quote' />
</div>
<div>
  <input type='submit' id='tmpQuote2' value='View Quote' />
</div>
<div>
<p id="paragraph"> some text that will disappear</p>
</div>

$(document).ready(
function() {
$('p').mouseover(
function(){
$(this).replaceWith("<p> the text changed to this text </p>");
}
);

$('input#tmpQuote1').click(
  function($e) {
    $e.preventDefault();

    $(this).replaceWith(
      "<p>\n" +
      "  I would imagine that if you could understand \n" + 
      "  Morse code, a tap dancer would drive you crazy.\n" +
      "</p>\n"
    );
  }
);

$('input#tmpQuote2').click(
  function($e) {
    $e.preventDefault();

    $(this).replaceWith(
      "<p>\n" +
      "  I'd like to get four people who do cart wheels \n" +
      "  very good, and make a cart.\n" +
      "</p>\n"
    );
  }
);

Basically when I hover over the the last paragraph it changes text . when I click on those two buttons they do change to paragraphs + text. so far so good. But the problem I'm having is understand开发者_如何转开发ing why when I hover over the first & second (newly spawned) paragraphs , the mouseover doesn't work. Is there a delay in Jquery parser. Or maybe I do not know exactly how $this works.

thanks


change .click into .live('click',function(){...}); and you'll be good. The reason is stated above: Event handlers are only added to content which is already there. If you want to add it to every content you add dynamically, you have to use .live.


This is because the event handler is not subscribed to the click events of the new <p>. You should either set the event handler manually after adding them to the document, or use .live('click', function...) or, better, jQuery.livequery plugin.


The functions you have created are only applied to all objects created when the document was created. Anything created later, i.e. added dynamically, will not get these event handlers.

See also this question: click() jquery function not available on new divs

Basically, to solve this, you need to use the jquery delegate function which will solve the problem.

(See here for explanation on why deligate() and not live())

0

精彩评论

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