gpt4 book ai didi

javascript - 使用 jquery 从动态添加的 html 代码调用函数

转载 作者:行者123 更新时间:2023-11-30 08:49:07 25 4
gpt4 key购买 nike

场景是这样的

$(document).ready(function(){
var rowIndex = 0;
var count = 0;
function callThisFunction(index, value, count) {
alert('called');
}

function dynamicContentAdd() {
rowIndex++;
count++;

var row = "<input name='input["+rowIndex+"]' onkeyup = 'callThisFunction("+rowIndex+","+total[1]+","+count+");' id='input"+rowIndex+"' type='text' class='inputfield' />";

$("#table").append(row);
}

我通过单击按钮调用了函数 dynamicContentAdd(),它工作正常。但是不起作用的是它没有在 keyup 上调用函数 callThisFunction()。它给出了函数未定义的错误。但是当我在外部 js 文件中具有相同的功能时,它会成功调用它。这不是在 jquery 中从动态添加的 html 代码调用函数的方法吗?

请告诉我。

谢谢

最佳答案

问题是因为您使用的是内联事件处理程序,所以 js 引擎将在全局范围内查找函数 callThisFunction,但是您已将函数添加到 dom 就绪处理程序中,使其成为本地函数到 dom 就绪处理程序,这将导致 js 抛出错误。

解决方案 1. 将函数设为全局

//since the function is define outside of dom ready handler it is available in the global scope
function callThisFunction(index, value, count) {
alert('called');
}

$(document).ready(function () {
var rowIndex = 0;
var count = 0;

function dynamicContentAdd() {
rowIndex++;
count++;

var row = "<input name='input[" + rowIndex + "]' onkeyup = 'callThisFunction(" + rowIndex + "," + total[1] + "," + count + ");' id='input" + rowIndex + "' type='text' class='inputfield' />";

$("#table").append(row);
}
})

$(document).ready(function () {
var rowIndex = 0;
var count = 0;

//define the function as a property of the window object again making it available in the public scope
window.callThisFunction = function (index, value, count) {
alert('called');
}

function dynamicContentAdd() {
rowIndex++;
count++;

var row = "<input name='input[" + rowIndex + "]' onkeyup = 'callThisFunction(" + rowIndex + "," + total[1] + "," + count + ");' id='input" + rowIndex + "' type='text' class='inputfield' />";

$("#table").append(row);
}
})

解决方案 2:jQuery 方式 - 使用具有 data-* 属性的委托(delegate)事件处理程序

$(document).ready(function () {
var rowIndex = 0;
var count = 0;

$('#table').on('keyup', '.myfncaller', function(){
var $this = $(this);
var index = $this.data('index'), value = $this.data('value'), count = $this.data('count');
})

function dynamicContentAdd() {
rowIndex++;
count++;

var row = "<input name='input[" + rowIndex + "]' id='input" + rowIndex + "' type='text' class='inputfield myfncaller' data-index='" + rowIndex + "' data-value='" + total[1] + "' data-count='" + count + "' />";

$("#table").append(row);
}
})

关于javascript - 使用 jquery 从动态添加的 html 代码调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19417274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com