gpt4 book ai didi

javascript - 是否可以将 onclick 事件添加到 jQuery 生成的输入字段中?

转载 作者:行者123 更新时间:2023-12-01 00:32:38 24 4
gpt4 key购买 nike

这是我正在尝试运行的代码。

            var inputText = $('<input>', {
type: 'text',
name: id,
onclick: function() {
$('#' + nextQuestion).show();
}
});

但是,当我检查 DOM 和生成的 jQuery 对象时,onclick 方法为 null。我的语法有错误吗?

Your permanent name DOM object

最佳答案

基于这两个答案What's the difference between "click" and "onclick" when creating an element with jQuery? , .prop() vs .attr()

An attribute value may only be a string whereas a property can be of any type.

因此,onclick 创建一个属性,并且值应该是引用函数的字符串。

var inputText = $('<input>', {
type: 'text',
name: id,
onclick: "somefunction()"
});

somefunction() {}

click在元素上创建一个属性,值应该是一个实际的函数。

 var inputText = $('<input>', {
type: 'text',
name: id,
click: function () {
$('#' + nextQuestion).show();
}
});

关于javascript - 是否可以将 onclick 事件添加到 jQuery 生成的输入字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58385991/

24 4 0