javascript jquery点击输入[type='']不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25628080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery click input[type=''] doesn't work
提问by Bak
I have a problem with .click() event in jquery. I create an input tag with a button, and then when I click this tag it must show an alert message. But it doesn't work. Here is the HTML code:
我在 jquery 中遇到了 .click() 事件的问题。我创建了一个带有按钮的输入标签,然后当我单击此标签时,它必须显示一条警报消息。但它不起作用。这是 HTML 代码:
<div id="test">
</div>
<input type="button" id="btn" value="Submit" />
And the Jquery code:
和 Jquery 代码:
$("#btn").click(function(){
html = "<input type='text' size='1' name='courses[]' value='1' />";
$("#test").after(html);
});
$("input[type='text']").on("click", function(){
alert('ppp');
});
All libraries of jquery are linked in the real site. Here is an example in jsFiddle: http://jsfiddle.net/82pps6Lz/29/Thanks
jquery的所有库都在真实站点中链接。这是 jsFiddle 中的一个例子:http: //jsfiddle.net/82pps6Lz/29/谢谢
回答by VisioN
Think, you insert a new <input>
element only when you click on the button, but you bind a click
event straight away, when the <input>
element doesn't yet exist. So you either should bind the event after (or during) element insertion:
想一想,您<input>
只有在单击按钮时才插入一个新元素,但是click
当该<input>
元素尚不存在时,您会立即绑定一个事件。因此,您应该在元素插入之后(或期间)绑定事件:
$('#btn').click(function(){
var html = "<input type='text' size='1' name='courses[]' value='1' />";
$(html).on('click', function() {
// ...
}).insertAfter('#test');
});
... or use the DOM event delegation:
...或使用DOM 事件委托:
$('#btn').click(function(){
var html = "<input type='text' size='1' name='courses[]' value='1' />";
$('#test').after(html);
});
$(document).on('click', 'input[type="text"]' function() {
// ...
});
回答by Amit Joki
回答by levi
You need to bind the input after insertion. because when you perform $("input[type='text']")
the input
not exists. it exists until you click on submit
.
插入后需要绑定输入。因为当你执行$("input[type='text']")
的input
不存在。它一直存在,直到您单击submit
。
$("#btn").click(function(){
html = "<input type='text' size='1' name='courses[]' value='1' />";
$("#test").after(html);
$("input[type='text']").on("click", function(){
alert('ppp');
});
});