Pregunta

Follow w3schools

The triggerHandler() method is similar to the trigger() method. 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

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

then both of them are affected . Here's my code:

HTML:

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

JavaScript:

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

Live Copy on jsFiddle

¿Fue útil?

Solución

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. 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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top