我想通过js创建运行时输入,并设置类,但是在创建输入后,我想按类调用无法工作,为什么?
=> HTML代码
button type="button" onclick="AddInput()">New Button</button>
<div id="priverw"> </div>
=> JS代码
function AddInput() {
var newInp = "<input type='button' class='runtime' value='Run' />";
$('#priverw').html(newInp);
}
$('.runtime').click(function () {
alert('ok');
})
答案 0 :(得分:0)
功能不是自执行的。如果要在文档加载时运行此文件,请执行以下操作:
function AddInput() {
var newInp = "<input type='button' class='runtime' value='Run' />";
$('#priverw').html(newInp);
}
$('.runtime').click(function () {
alert('ok');
})
$( document ).ready(function() {
// run the AddInput func
AddInput()
});
答案 1 :(得分:0)
仅在创建DOM元素之后注册事件监听器。
function AddInput() {
var newInp = "<input type='button' class='runtime' value='Run' />";
$('#priverw').html(newInp);
}
AddInput();
$('.runtime').click(function () {
alert('ok');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button type="button" onclick="AddInput()">New Button</button>
<div id="priverw">
</div>
答案 2 :(得分:0)
您没有调用函数来添加按钮。 .click
侦听器仅初始化当前可用的元素。如果以后创建新元素,则不会将事件侦听器添加到新创建的元素中。因此,您需要在添加新元素之后一次又一次添加事件侦听器。
function AddInput() {
var newInp = "<input type='button' class='runtime' value='Run'/>";
$('#priverw').html(newInp);
$('.runtime').click(function () {
alert('ok');
});
}
AddInput();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="priverw"></div>