jQuery ajax的each循环中调用alert函数提示未定义如何解决
问题原因
你的所有代码都包裹在(function() { ... })() 立即执行函数的私有作用域中,在这个作用域内部声明的myFunction默认仅在函数内部可访问,不会挂载到全局window对象上。而行内onclick属性绑定的事件触发时,会从全局作用域查找调用的函数,因此会抛出myFunction is not defined的错误。
解决方案
方案1:将函数挂载到全局作用域(改动最小)
直接把你的myFunction定义挂载到window对象上,全局作用域就可以访问到:
(function() { // 把函数挂载到全局window对象 window.myFunction = function() { alert("I am an alert box!"); } // 你原来的循环代码 const editText = (text) => `<p class="d-inline"><</p><p class="d-inline">${text.replace('<','').replace('>','')}</p><p class="d-inline">></p>`; $.ajax({ type: "GET", url: "/clinical/bbr-message-template-legend-list", dataType: "json", success: function (response){ var tbody=""; $.each(response.all_legends, function (key, legend) { tbody+='<tr>'+ '<td><a href="#" onclick="myFunction()">'+editText(legend.value)+'</a></td>'+ '<td>'+legend.text+'</td>'+ '</tr>'; }); $('#legend-list tbody').html(tbody) } }); })()
方案2:使用事件委托(更规范,避免全局污染)
不使用行内onclick绑定,改用jQuery的事件委托机制绑定动态生成元素的点击事件,不需要暴露全局函数:
- 首先修改动态生成的a标签,去掉
onclick属性,添加自定义类方便选择:
// 把原来拼接tbody的对应行改成下面这样 '<td><a href="#" class="legend-tag">'+editText(legend.value)+'</a></td>'+
- 在IIFE内部直接绑定委托事件即可:
(function() { // 预先绑定事件委托,父级选择页面初始就存在的#legend-list即可 $('#legend-list').on('click', '.legend-tag', function(e) { e.preventDefault(); // 可选,阻止a标签默认跳转行为 alert("I am an alert box!"); }) const editText = (text) => `<p class="d-inline"><</p><p class="d-inline">${text.replace('<','').replace('>','')}</p><p class="d-inline">></p>`; $.ajax({ type: "GET", url: "/clinical/bbr-message-template-legend-list", dataType: "json", success: function (response){ var tbody=""; $.each(response.all_legends, function (key, legend) { tbody+='<tr>'+ '<td><a href="#" class="legend-tag">'+editText(legend.value)+'</a></td>'+ '<td>'+legend.text+'</td>'+ '</tr>'; }); $('#legend-list tbody').html(tbody) } }); })()
内容的提问来源于stack exchange,提问作者user16409170
相关产品推荐
相关产品推荐

