开发者

No alert popping up, although variable is defined, and syntax LOOKS correct

Here's my code:

$(document).ready(function(){

  var Bold="Yes!  There is bold in the text above!!";
  var NoBold="No... There isn't any bolded text in the paragraph above..";
  var BoldButton='<input class="BoldButton" type="button" value="Bold?" id="WelcomeBoldButton">';

  $(BoldButton).insertAfter('#intro');
  $(BoldButton).insertAfter('#LatestNews');

  $(BoldButton).click(function(){
    if($(this).prev().is(':has(b, strong)')){
      alert(Bold);
      } else {
 开发者_如何学Go       alert(NoBold);
      }
});

});

For some reason, the alert won't pop up upon clicking the instances of the variables even though the buttons are showing up..

UPDATE:

Here is a working version of the code. I apologize but I'm still very new to JS and jQuery but I don't really understand why this version is working..

$(document).ready(function(){

  var Bold="Yes, some of this text is Bolded!";
  var NoBold="No, none of this text is Bolded..";
  var BoldButton='<input class="BoldButton" type="button" value="Bold?">';
  var MakeMeMoreBoldButton='<input class="MakeMeMoreBoldButton" type="button" value="MakeMe More Bold!">';
  var MakeMeBoldButton='<input class="MakeMeBoldButton" type="button" value="Make Me       Bold!">';

  $(BoldButton).insertAfter('#disclaimer');
  $(BoldButton).appendTo('#navigation');
  $(BoldButton).insertAfter('#intro');

  $('.BoldButton').click(function(){
  if($(this).prev().is(':has(b, strong)')){
  alert(Bold);
  $(this).prev().addClass('BoldText');
  $(MakeMeMoreBoldButton).insertAfter(this).prev();
  $('.MakeMeMoreBoldButton').click(function(){
    $('.BoldText').css('font-weight', 'bold');
  });
  }  
else{
  alert(NoBold);
  $(this).prev().addClass('MakeMeBold');
  $(MakeMeBoldButton).insertAfter(this).prev();
  $('.MakeMeBoldButton').click(function(){
    $('.MakeMeBold').css('font-weight', 'bold');
  });
  }
  });
  });


That's not going to work, as you've demonstrated by empirical testing. What you're doing is creating some DOM content and then copying it a couple times into the document. You need to set up your "click" handlers on the real DOM nodes that are actually in the document.


Move the event handler before the insertions. A better way to do this, however, is this:

  $('.BoldButton').live('click',function{

     if($(this).prev().is(':has(b, strong)')){
       alert(Bold);
     } else {
       alert(NoBold);
     }
 });


Have you tried attatching the click event before inserting the buttons into the DOM.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜