使用 jquery 从动态添加的 html 代码调用函数
Call a function from Dynamically added html code using jquery
这是场景
$(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 ready 处理程序中添加了该函数,使其成为 dom ready handler 的本地函数,这将导致 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-* 属性的委托事件处理程序
$(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);
}
})
相关文章:
- 如何解析结构不良的 html 代码
- 我的html表单无法验证.请参阅代码片段中的html代码和java脚本
- 将第一个字母大写并去掉html代码
- 我在下拉列表中尝试了下一个和前五年的html代码.接下来的5年我都过得很好.我怎样才能拿到之前的5年
- 使用.format在一些HTML代码中插入文本,会出现错误(Python)
- html代码没有在记事本++上运行
- 来自mysql的动态值用于html代码点火器视图中的图形
- 如何:编写漂亮的HTML代码和Javascript控制台
- 我需要java代码来打开html代码onclick事件
- html代码需要可点击的文本按钮
- 是否可以在JavaScript中包含HTML代码
- 如果javascript打开/关闭,则隐藏和显示html代码
- 使用PartialView作为带有变量的可重悬浮html代码
- 在jquery中复制特定的html代码
- 如何在AngularJS的上下文中使用Google Chrome Developer Tool在HTML代码中设置断点
- 显示HTML代码块
- 从HTML代码中提取数据
- 如何获取保存在变量中的HTML代码的任何属性的值
- 将html代码转换为十六进制
- JavaScript和Html代码来运行所有类型的视频并获取状态