数组的HTML元素选择器

我需要为jQuery change事件选择一个输入字段数组。

<input id="LandDescriptionItems_0__Acres" name="LandDescriptionItems[0].Acres" ...
<input id="LandDescriptionItems_1__Acres" name="LandDescriptionItems[1].Acres" ...
<input id="LandDescriptionItems_2__Acres" name="LandDescriptionItems[2].Acres" ...

etc

当前有11个元素。我需要连接一个jQuery change()事件,以便每次更改时都能得到它们的总和。就像是:

_$form.find('#LandDescriptionItems_0__Acres').change(function(e) {
    e.preventDefault();

    ...

});

实际上,这只是我困扰的选择器。它像使用通配符一样简单吗?或者,还有更好的方法?

评论
  • 呐爱
    呐爱 回复

    The change event is most often associated with <select>. I'm not sure that's actually what you want since the user would need to type something and then focus somewhere else to fire the blur event on the input field in order for the change event to actually fire.

    Presuming you want to check each time either field's value has actually changed I suggest using keydown.

    If each element has the same class it's super easy to listen for any keydown events on every element, even dynamically, if we add the event listener to the entire document and use a selector to narrow down events we actually care about.

    I'm making a presumption here, since you used the word "sum" that you want to add the values together which I further presumed to be numbers. I'm using parseInt() to ensure we get a number value, or a 0 as a fallback.

    const watchedGroupSel = 'input.watchedGroup';
    const $watchedGroup = $(watchedGroupSel);
    
    const doSum = () => {
      const values = $watchedGroup.map(function() {
        const val = $(this).val();
        const num = val ? parseInt(val, 10) : 0;
    
        return num;
      })
      .get()
      .join()
      .split(',');
      
      return values.reduce((acc, cur) => parseInt(cur, 10) + acc, 0);
    }
    
    $(document).on('keyup', watchedGroupSel, () => console.log(doSum()));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <input type="number" class="watchedGroup" name="something[0]" />
    <input type="number" class="watchedGroup" name="something[1]" />
    <input type="number" class="watchedGroup" name="something[2]" />
    <input type="number" class="watchedGroup" name="something[3]" />

    The gist of this code is that we have a doSum() that will grab all the elements we care about, parse their values as numbers, and converting everything to an array so we can use reduce to do the sum.

    自从我使用jQuery以来已经过了一分钟,所以可能有一种更简单的方法...