我有什么:
- 我有一个文本框,它假定在相应的选择框中选择的任何选项的值。
- 我正在为 on change、mouseup、mousedown、mouseout、keyup 和 keydown 事件重复完全相同的函数
我需要什么:
是否可以将上述功能合二为一以生成更高效的代码?它看起来非常重复。
我的代码:
JSFiddle:http://jsfiddle.net/clarusdignus/843YW/1/
HTML:
<label>Industry:</label>
<select name="industry">
<option selected="selected"></option>
<option value="ag">Agriculture</option>
<option value="co">Corporate</option>
</select>
<input type="text" disabled="disabled" name="industryspecifier"/>
jQuery:
$('select[name=industry]').on('change', function() {
$('[name=industryspecifier]').val($(':selected',this).val());
});
$('select[name=industry]').on('mouseup', function() {
$('[name=industryspecifier]').val($(':selected',this).val());
});
$('select[name=industry]').on('mousedown', function() {
$('[name=industryspecifier]').val($(':selected',this).val());
});
$('select[name=industry]').on('mouseout', function() {
$('[name=industryspecifier]').val($(':selected',this).val());
});
$('select[name=industry]').on('keydown', function() {
$('[name=industryspecifier]').val($(':selected',this).val());
});
$('select[name=industry]').on('keyup', function() {
$('[name=industryspecifier]').val($(':selected',this).val());
});
最佳答案
只需将它们与空格组合起来即可:
$('select[name=industry]').on('change mouseup mousedown mouseout keydown', function() {
$('[name=industryspecifier]').val($(':selected',this).val());
});
作为docs for .on()状态:
events Type: String One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
关于javascript - 将 change、mouseup、mousedown、mouseout、keyup 和 keydown 组合到一个函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22822285/