I have an issue where I have the following jQuery and mark up working although if I move the location of textarea the .click() event doesn't fire. I haven't seen this $('element', something) before. What does the $wrapper syntax mean please? Thanks,

 this.each(function () {
     var $field = $(this);
     var $wrapper = $field.parent();


      $('.myClass', $wrapper)
          .click(function () { 
              // do stuff
          });

<div>
  <textarea></textarea>
  <img src="x" class="myClass" />
</div>
有帮助吗?

解决方案

This answer assumes that $(this) refers to the textarea, which isn't clear from your question.

The second parameter in $('.myClass', $wrapper) refers to the context of the first parameter. That is, the first parameter is a descendant of the second parameter.

If $field is your text area, the context of .myClass is the parent of the textarea (as that is how you've defined $wrapper).

If you move the textarea out of the DIV that also contains .myClass, your context changes. Since .myClass is no longer in that context, the event handler is not bound to it.

If you want the click event bound to .myClass irrespective of context, use:

$('.myClass').click(function () { 
     // do stuff
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top