简体   繁体   English

jQuery on.click问题

[英]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. 当我单击#incrementBtn时,它们两个都应增加一个计数器。

Here are the samples (and I will provide all the code for further clarifications): 以下是示例(我将提供所有代码以供进一步说明):

1 1

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

2 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/ 这是完整的工作代码: 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. 您将onclick处理程序应用于元素之前,已将其动态插入到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). 主体处理程序之所以起作用,是因为它正在侦听来自与该#incrementBtn选择器匹配的元素中的body元素上的点击事件(事件会冒泡)(稍后是否将其添加到页面中无关紧要)。

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'>); 此语法无效的Javascript: $(<'textarea'>); You've added some random <> there. 您已经在其中添加了一些随机<>。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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