如您所见,我的输入和选择正在执行一个函数。在该函数中,我需要检测哪个输入或选择被修改并获取其值。
我该怎么做?找不到适合我的需求的好的答案。
<input type="text" name="1" id="1" onchange="some_function"/>
<input type="text" name="2" id="2" onchange="some_function"/>
<select name="3" id="3" onchange="some_function">
<option></option>
</select>
<select name="4" id="4" onchange="some_function">
<option></option>
</select>
最佳答案
首先,不要使用事件属性。使用不显眼的事件处理程序连接您的事件。
其次,要解决您的实际问题,您可以在事件处理程序中使用 this
关键字来引用引发事件的元素。从那里您可以检索元素所需的属性。当你使用 jQuery 时,你可以这样做:
jQuery(function($) {
$('input').on('input', some_function);
$('select').on('change', some_function);
});
function some_function() {
console.log(`${this.name} = ${this.value}`);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="1" id="1" />
<input type="text" name="2" id="2" />
<select name="3" id="3">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<select name="4" id="4">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
关于javascript - 检测哪个输入/选择被更改并获取其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182763/