我需要为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 entiredocument
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 a0
as a fallback.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以来已经过了一分钟,所以可能有一种更简单的方法...