动态新增select标签后如何让其绑定的onchange事件正常生效
问题排查
你的代码存在4个核心问题导致功能异常:
- 初始页面的
select的onchange属性值为handicap,缺少函数执行的括号,初始select本身就无法触发事件 - 动态拼接HTML时写错了标签,第二行选项错误使用了
<select>标签,应该是<option>,导致生成的DOM结构异常 - 所有动态生成的元素复用了相同的
id属性,而id在DOM中是全局唯一的,document.getElementById只会返回第一个匹配的元素,无法匹配新增元素对应的内容 handicap函数逻辑绑定了固定id,无法区分当前触发事件的是哪一个select,也找不到对应的input输入框
修复方案
这里给你两种修复方式,推荐使用第二种事件委托的写法,可维护性更高:
方式1:修改内联事件传参适配动态元素
先修正HTML和JS逻辑:
<div id="ugh"> <!-- 初始select加括号,并且把自身和对应的input作为参数传入 --> <select onchange="handicap(this, document.getElementById('cap'))"> <option value="5"> Example (5)</option> <option value="10"> Example (10)</option> </select> <input id="cap" type="text"> </div> <a id="sigepa" class="fa fa-clone" style="font-size:30px"></a> <!-- 确保页面已引入jQuery库 --> <script> $('#sigepa').click(function(){ // 生成唯一标识区分不同组的元素 const uniqueId = Date.now(); let ako = ''; // 修正写错的option标签,事件传入当前select和对应的input ako += `<select onchange="handicap(this, document.getElementById('cap_${uniqueId}'));">`; ako += `<option value="5"> Example (5)</option>`; ako += `<option value="10"> Example (10)</option>`; ako += `</select>`; ako += `<input id="cap_${uniqueId}" type="text">`; $('#ugh').append(ako); }); // 接收触发事件的select和对应input作为参数 function handicap(selectEle, inputEle) { // 直接拿当前选中的option的value值即可,不需要单独找option inputEle.value = selectEle.value; } </script>
方式2:使用jQuery事件委托(更推荐)
完全移除内联onchange,用事件委托绑定所有动态生成的select,逻辑更简洁:
<div id="ugh"> <select class="handicap-select"> <option value="5"> Example (5)</option> <option value="10"> Example (10)</option> </select> <input class="cap-input" type="text"> </div> <a id="sigepa" class="fa fa-clone" style="font-size:30px"></a> <!-- 确保页面已引入jQuery库 --> <script> $('#sigepa').click(function(){ let ako = ''; // 不需要内联事件,用class标识即可 ako += `<select class="handicap-select">`; ako += `<option value="5"> Example (5)</option>`; ako += `<option value="10"> Example (10)</option>`; ako += `</select>`; ako += `<input class="cap-input" type="text">`; $('#ugh').append(ako); }); // 事件委托:绑定父元素#ugh,匹配所有子元素.handicap-select的change事件,动态生成的元素也能生效 $('#ugh').on('change', '.handicap-select', function() { // 找当前select同组的下一个input元素赋值 $(this).next('.cap-input').val($(this).val()); }); </script>
内容的提问来源于stack exchange,提问作者Aldrin Atolle
相关产品推荐
相关产品推荐

