我正在将 input
元素动态添加到 table
中,id
为 inputDataElements
。
这些input
元素的名称为deleteAction
:
function renderInputDataRows(inputData) {
var rows = "";
for (var i = 0; i < inputData.length; i++) {
rows += '<tr>' +
// ...
'<td class="rowActions">' + \
'<input type="image" ' + \
' style="position:relative; ' + \
' bottom:-2px; ' + \
' left:-4px; ' + \
' padding-right:2px;" ' + \
' src="images/delete.png" ' + \
' onClick="deleteInputDataRow(' + inputData[i].index + ');"' + \
' name="deleteAction" ' + \
' value="deleteInputDataRow' + inputData[i].index + '"' + \
' size="18,18" ' + \
' border="0" />' + \
'</td>' +
// ...
'</tr>';
}
return rows;
}
问题:我想捕获 deleteAction
命名的 input
元素上的 mouseover
事件。
我有以下 jQuery 脚本:
$(document).ready(function() {
inputDataElementsRowDeleteActions = $("#inputDataElements input:[name=deleteAction]");
...
inputDataElementsRowDeleteActions.mouseover(function(event) {
alert(event);
});
});
问题:当我将鼠标悬停在 input
元素上时,我没有收到 alert
消息。
当动态添加元素时,有没有办法用 jQuery 捕获 mouseover
事件?
最佳答案
最简单的方法是使用.live()
inputDataElementsRowActions.live('mouseover', function(event) {
alert(event);
});
或者您可以使用类似的.delegate()
(在这种情况下可能是首选)。
$("#inputDataElements").delegate('input[name=rowAction]', 'mouseover', function(event) {
alert(event);
});
它们都通过捕获冒泡的事件来工作。在本例中,.live()
在根处捕获它,而 .delegate()
在 #inputDataElements
处捕获它。
否则,您必须在创建元素时(或之后)绑定(bind)事件。
关于javascript - 如何使用 jQuery 捕获动态添加的输入 HTML 元素上的鼠标悬停事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3376153/