简体   繁体   English

triggerHandler() 影响所有匹配的元素

[英]triggerHandler() affects all matched element

Follow w3schools关注w3schools

The triggerHandler() method is similar to the trigger() method. triggerHandler() 方法类似于 trigger() 方法。 Except that it does not trigger the default behavior of an event (like form submission) and it only affects the first matched element.除了它不会触发事件的默认行为(如表单提交)并且它只影响第一个匹配的元素。

But I test with 2 input tag and use但我用 2 个输入标签进行测试并使用

$("input").triggerHandler("select");

then both of them are affected .那么他们两个都会受到影响。 Here's my code:这是我的代码:

HTML: HTML:

<input type="text" name="FirstName" value="Hello World" />
<input type="text" name="FirstName" value="Hello" />

JavaScript: JavaScript:

$(document).ready(function(){
  $("input").select(function(){
    $("input").after(" Input select event occured!");
  });
  $("button").click(function(){
    $("input").triggerHandler("select");
  });
});

Live Copy on jsFiddle jsFiddle 上的实时复制

The event is only being triggered on the first element.该事件仅在第一个元素上触发。 Your code, though, is outputting two lines when that happens:但是,当发生这种情况时,您的代码会输出行:

$("input").after(" Input select event occured!");

That line, run once , will append the text after all matching input elements.该行 run once将在所有匹配的input元素之后追加文本。 Since there are two matching elements, you see the line twice even though the event only fired for the first element.由于有两个匹配的元素,即使事件只为第一个元素触发,您也会看到该行两次。

Just change that one line to只需将这一行更改为

$(this).after(" Input select event occured!");

...and you'll see the output appended only after the element on which the event was triggered. ...您将看到输出仅附加在触发事件的元素之后。 Live Copy , with just the change above and removing the option to include MooTools on the page. Live Copy ,仅进行上述更改并删除在页面上包含 MooTools 的选项。

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

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