Javascript 如何将值从一个函数传递到HTML回调?
我想将Javascript 如何将值从一个函数传递到HTML回调?,javascript,dom,Javascript,Dom,我想将sno值传递给另一个函数 var sno=10; row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord('sno');'"; editRecord('sno')正在传递字符串“sno”,您需要像这样传递变量:editRecord(sno)您已经用这一行传递了它:onclick='editRecord(sno);' 只需删除sno中的'from'即可。使用我为您编写的以下行: 代码
sno
值传递给另一个函数
var sno=10;
row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord('sno');'";
editRecord('sno')
正在传递字符串“sno”,您需要像这样传递变量:editRecord(sno)代码>您已经用这一行传递了它:onclick='editRecord(sno);'
只需删除sno中的'from'即可。使用我为您编写的以下行:
代码
function editRecord(mySno){}
//当sno为整数时
var-sno=10
行.insertCell(6).innerHTML=“输入类型='button'值='edit'onclick='editRecord(“+sno+”)”
//当sno是字符时
var sno='C'
row.insertCell(6).innerHTML=“输入类型='button'值='edit'onclick='editRecord(\'”+sno+“\');” 决不能在双四分之一或单四分之一中使用双四分之一。
这不是真的。
“xxxxx”YYYY“xxxx”
你可以用
“xxxxx'YYYY'xxxxx”
或
“xxxxx\'YYYY\'xxxx”
或
“xxxx”+“yyyyy”+“xxxx”
var-sno=10;
row.insertCell(6.innerHTML=“输入类型='button'值='edit'onclick='editRecord('+sno+');” 尽量不要混用代码
创建HTML元素
此方法不仅比字符串innerHTML快,还允许您将输入作为JavaScript对象处理
var newRow = row.insertCell(6),
input = document.createElement('input');
您已经创建了新行,但如果您没有创建新行,则可以清除行内的代码:
input.type = 'button';
input.value = 'edit';
input.onclick = editRecord;
最后,将输入附加到row元素:
newRow = (function clearHtmlElement (el){
var newEl = el.cloneNode();
el.parentNode.replaceChild(newEl, el);
return newEl;
}(newRow));
在HTML元素范围内保存您的值
然后,您可以使用以下属性保存您的值:
newRow.appendChild(input);
或
也可以将其保存到HTML元素中:
input.setAttribute('data-sno', 10);
在函数中使用您的值
选择使用它的方式,或者像我在这里做的那样使用它们。现在您的函数中有了sno
,更重要的是,它可以是您想要的JavaScript对象
更新:以适应功能的使用
如果您想使用在问题上定义的函数,那么在定义onclick处理程序时,必须执行以下操作:
function editRecord () {
var sno = this.sno
|| this.getAttribute('data-snow')
|| this.dataset.snow;
...
}
这里,使用作用域,mySno
将在每次定义onclick处理程序时保存sno
值的引用。但是这对对象不起作用,所以只有数字或字符串起作用。。。另外,它有点难看。Er,editRecord(sno)
?尝试editRecord(sno)
您可以将其分配给变量var variable=sno
,然后将variable
传递给其他函数,该函数是全局变量,它每行都会增加。。我尝试editRecord(sno),但它采用全局变量值(最后一行值)@Andy@ZainFarooq大福真的吗?那没有意义^^它不起作用。。。actual是逐行递增的全局变量,它给出了最后一行的值It's not working错误:uncaught syntaxerror意外标记删除两个斜杠后重试()
input.setAttribute('data-sno', 10);
input.sno = 10;
function editRecord () {
var sno = this.sno
|| this.getAttribute('data-snow')
|| this.dataset.snow;
...
}
input.onclick = (function(){
var mySno = sno;
return function(){
editR(mySno);
};
}());