JQuery代码如下:
$(function () {
$('#skillKey').on('click', 'tr', function () {
$(this).css('color','red');
$(this).keyup(function(){
alert(123)
});
});
})
为什么点击后元素变色,而通过键盘输入,无法alert?通过$(document).keyup()确实可以达到效果,想知道其中原因。有可能与keyup()要求绑定的元素类型有关?
另:一种错误的keyup()函数调用方法,若这样写:
jQuery 1.12.4
jQuery 1.12.4是jQuery 1.x系列的最后一个正式稳定版本,由jQuery团队于2016年发布。该版本主要面向需要兼容旧版浏览器环境的网站和Web应用,尤其适用于仍需支持Internet Explorer 6、Internet Explorer 7、Internet Explorer 8等老旧浏览器的项目。
下载
$(function () {
$('#skillKey').on('click', 'tr', function () {
$(this).css('color','red');
$(this).keyup(alert(123));
});
})
那么点击tr后元素变色的同时会弹窗123,这是为什么?
先指出你的一个错误点
$('#skillKey').on('click', 'tr', function () {
$(this).css('color','red');
$(this).keyup(function(){
alert(123)
});
});
你这样绑定事件,结果是点击一次tr绑定一次,点了多少次就绑定了多少次,这个例子还是不明显,你在tr里放置一个input,然后编写如下代码,看看效果如何
$('#skillKey').on('click', 'input', function () {
$(this).css('color','red');
$(this).blur(function(){
alert(123)
});
});
再给个建议
需要使用的元素可以先缓存,不要滥用$,易读的前提下可以使用链式
$('#skillKey').on('click', 'tr', function () { var $this = $(this);
$this
.css('color', 'red')
.keyup(function () {
alert(123)
});
});