简体   繁体   English

'this'指的是jQuery on()中动态生成的错误元素

[英]'this' refers to wrong dynamically generated element in jQuery on()

As part of a dynamic form I have a checkbox field that enables and disables the next input field (they are a pair, so when you add a new section to the form, the checkbox and the input field are both added together). 作为动态表单的一部分,我有一个复选框字段,用于启用和禁用下一个输入字段(它们是一对,因此当您向表单添加新部分时,复选框和输入字段都会一起添加)。

.form-element
  .checkbox
    = f.label :foo_bool_field do
      = f.check_box :foo_bool_field, class: 'foo-bool-field-form-toggle'
      .desc_foo_bool_field= "text describing field"

  .input
    = f.label :bar_input_field
    = f.text_field :bar_input_field, disabled: f.object.foo_bool_field

and it's all in a .form class block. 它都在.form类块中。

Here is the code that does the disabling 以下是执行禁用的代码

$('.form').on('change', '.foo-bool-field-form-toggle', function(e) {
  // disabling code goes here
});

If I add a few of these form elements, then click on the text "text describing foo_bool_field", it enables/disables the input form of the first set only. 如果我添加一些这些表单元素,然后单击文本“文本描述foo_bool_field”,它只启用/禁用第一组的输入表单。 If I throw a debugger above the form disabling code and check this , the this always returns the first set. 如果我在调试表上方抛出一个调试器并禁用代码并检查this ,则this总是返回第一个集合。 If I click the actually text box □, it works properly, disabling the check boxes and referring to the right this of the checkbox that I actually clicked on. 如果我点击的实际文本框□,它工作正常,禁用复选框,并引用了正确的this ,我其实点击的复选框。

Any ideas? 有任何想法吗? I've tried a few different things ( click instead of change , etc), but it all comes back to the fact that when clicking on the text, this is not the element i clicked on, and I can't seem to get past that. 我尝试了一些不同的东西( click而不是change等),但这一切都回到了这样一个事实,当点击文本时, this不是我点击的元素,我似乎无法过去那。

Unlike most languages, this in javascript usually refers to the parent calling object, which can be almost anything depending on the context. 与大多数语言不同, this在javascript中通常是指父调用对象,它几乎可以取决于上下文。

Long story shory, try wrapping this in the jQuery selector like so: 说来话长shory,尝试包裹this在jQuery选择像这样:

$('.form').on('change', '.foo-bool-field-form-toggle', function(e) {
  // disabling code goes here
  $(this).whatever
});

Basically, $(this) will refer to the DOM element which triggered the callback event (ie change ), and will work for click or any other event trigger. 基本上, $(this)将引用触发回调事件(即change )的DOM元素,并且将用于click或任何其他事件触发器。

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

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