点击特定按钮显示对应消息的JavaScript实现问题
解决按钮点击事件提前执行的问题
嘿,我一眼就看出问题所在啦——你给按钮绑定点击事件的时候,直接执行了showAlert()函数,而不是把它作为点击触发的回调函数。这就导致页面一加载,三个showAlert就全跑了,点击按钮反而没反应。
问题根源
你现在写的代码是这样的:
p1.onclick = showAlert('msghello.txt');
这里的showAlert('msghello.txt')会立即执行,并把函数的返回值(这里是undefined)赋值给onclick,完全不是你想要的“点击时执行”的效果。
解决方案
你需要给onclick传递一个函数引用,而不是函数执行的结果。这里有两种常用的方法:
方法1:用匿名函数包裹
把showAlert调用放在一个匿名函数里,这样只有点击按钮时才会执行这个匿名函数,进而调用showAlert:
function init() { var p1 = document.getElementById('btn-hello'); var p2 = document.getElementById('btn-web'); var p3 = document.getElementById('btn-prive'); p1.onclick = function() { showAlert('msghello.txt'); }; p2.onclick = function() { showAlert('msgweb.txt'); }; p3.onclick = function() { showAlert('msgprive.txt'); }; function showAlert(file) { $.get(file, function(data) { alert(data); }, 'text'); } }
方法2:使用bind()绑定参数
Function.prototype.bind()可以帮你预先绑定函数的参数,同时返回一个新的函数,这样点击时就会带着指定参数执行:
function init() { var p1 = document.getElementById('btn-hello'); var p2 = document.getElementById('btn-web'); var p3 = document.getElementById('btn-prive'); p1.onclick = showAlert.bind(null, 'msghello.txt'); p2.onclick = showAlert.bind(null, 'msgweb.txt'); p3.onclick = showAlert.bind(null, 'msgprive.txt'); function showAlert(file) { $.get(file, function(data) { alert(data); }, 'text'); } }
这里的null是用来绑定this的,如果你的showAlert里不需要用到this,传null就行;如果需要用按钮本身的this,可以把null换成对应的按钮元素(比如p1)。
额外小提示
如果按钮数量多,你还可以优化代码,给按钮统一加一个类,然后通过事件委托来绑定,这样不用一个个获取元素绑定,比如:
<!-- 给按钮加共同的类 --> <button class="msg-btn" data-file="msghello.txt">Hello</button> <button class="msg-btn" data-file="msgweb.txt">Web</button> <button class="msg-btn" data-file="msgprive.txt">Prive</button>
function init() { document.addEventListener('click', function(e) { if (e.target.classList.contains('msg-btn')) { var file = e.target.dataset.file; showAlert(file); } }); function showAlert(file) { $.get(file, function(data) { alert(data); }, 'text'); } }
这种方式更简洁,后期加新按钮也不用改JS代码~
内容的提问来源于stack exchange,提问作者RagingDeathWish
相关产品推荐
相关产品推荐

