如何通过通过Javascript创建的html对象(按钮)使用jQuery执行事件? [英] How do I execute an event using jQuery through an html object(button) created through Javascript?
问题描述
我只是新来的.所以这就是我被困住的地方:
I'm just new here. So here's where I'm stuck:
我使用javascript创建了一个html表.我有一个按钮,单击该按钮会创建一组结构完全相同的表,但是这些表中的对象(例如按钮,文本)具有不同的ID.现在,当我尝试使用jQuery在生成的表之一上执行带有按钮的click函数时,它将无法正常工作.我怎么在这里转转?预先感谢!
I created an html table using javascript. I have a button,which when clicked, will create set of tables with exactly the same structure but the objects(eg. button, text) inside those tables have different ID's. Now when I try to execute a click function using jQuery with a button on one of the produced tables, it won't work. How do I go around here? Thanks in advance!
这是一个示例函数,可在javascript中创建html表(具有唯一ID):
Here's a sample function which creates the html table(with unique ID's) in javascript:
function CreateTables() {
var html = ' ';
var valPrompt = prompt("How many tables would you like to add?");
parseInt(valPrompt);
for (i = 1; i <= valPrompt; i++) {
html += "<table>" + "<tr>" + "<td>" + "Text goes here" + "</td>" + "<td>" + "<input type='text' id='txtTEXT" + i + "'/>" + "</td>" + "<td>" + < input type = 'button'
id = 'btnALERT" + i + "' / > +"</td>" + "</tr>" + "</table>"
}
document.getElementById('HtmlPlaceHolder').innerHTML = html;
}
因此,如果我们查看代码,则执行功能 CreateTables 时,将创建带有唯一ID的带有按钮的表集(btnALERT).为了选择对象,我想我将使用jQuery.因此,例如,如果我在btnALERT1(由CreateTables生产)中绑定处理程序,则说一个单击功能以提醒一个简单的"Hello",我该怎么做?我的代码似乎无效:
So, if we review the code, Sets of table with buttons(btnALERT) with unique ID's will be created if the function CreateTables is executed. In order to select the objects, I suppose I'll be using jQuery. So for example, if I bind a handler in btnALERT1(produced by CreateTables) say a click function in order to alert a simple "Hello", how will I do this? My code for this doesn't seem to work:
$(document).ready(function() {
$('#btnALERT1').click(function() {
alert("Hello");
});
});
推荐答案
使用 .live() (对于较旧的jquery版本-< v1.7):
Use .live() (for older jquery versions - < v1.7):
$('#btnALERT1').live('click', function()
{
alert("Hello");
});
或者:
$(document).delegate('#btnALERT1', 'click', function()
{
alert("Hello");
});
使用 .on()(对于新的jquery版本-> = 1.7):
Use .on() (for new jquery versions - >= 1.7):
$(document).on('click', '#btnALERT1', function()
{
alert("Hello");
});
这篇关于如何通过通过Javascript创建的html对象(按钮)使用jQuery执行事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!