No warning appears, although the variable is defined and the LOOKS syntax is correct

Here is 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 {
        alert(NoBold);
      }
});

});

For some reason, a warning will not appear when clicking on instances of variables, even if the buttons are displayed up.

UPDATE:

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

$(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');
  });
  }
  });
  });
+3
source share
3 answers

This will not work, as you have shown in empirical testing. What you are doing is creating some DOM content and then copying it a couple of times to the document. You need to configure the click handlers on the actual DOM nodes that are actually in the document.

+4

. :

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

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

You tried to get a click event before inserting buttons in the DOM.

0
source

Source: https://habr.com/ru/post/1757232/


All Articles