简体   繁体   中英

Jquery on.click issue

I've got two code samples, the first one is working properly, the second one isn't. Both of them should increase a counter when I click on the #incrementBtn.

Here are the samples (and I will provide all the code for further clarifications):

1

$('body').on('click','#incrementBtn', function(){
  let textAreaValue = parseInt($('textarea').val());
  $('textarea').val(textAreaValue+1)
});

2

$('#incrementBtn').on('click', function(){
  let textAreaValue = parseInt($('textarea').val()); 
  $('textarea').val(textAreaValue+1)
});

And one more question, what is the difference between using this (code doesn't work):

let textArea = $(<'textarea'>);      

let textAreaValue = parseInt(textArea.val());
textArea.val(textAreaValue+1);

And this (code works):

let textAreaValue = parseInt($('textarea').val());
$('textarea').val(textAreaValue+1)

Here is the full working code: https://jsfiddle.net/wjnjdk72/3/

First issue:

You're applying the onclick handler to the element before you've inserted it dynamically into the DOM. The body handler works because it's listening for click events on the body element (which bubble up to it) from an element that matches that #incrementBtn selector (it doesn't matter if it's added to the page later on).

You can see this in action by swapping the order, if you add the element first it works:

incrementCounter('#wrapper'); // add the element first

$('#incrementBtn').on('click', function(){
  let textAreaValue = parseInt($('textarea').val()); 
  $('textarea').val(textAreaValue+1)
});

Second issue:

This syntax is invalid Javascript: $(<'textarea'>); You've added some random <> there.

使用jQuery时,您仅选择名称为“ textarea”的HTML标记即可,无需包含<>字符

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM