[英]how can pass values from one function to an HTML callback?
var sno=10;
row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord('sno');'";
我想將sno
值傳遞給另一個函數。
function editRecord(mySno){}
盡量不要混合代碼。
var newRow = row.insertCell(6),
input = document.createElement('input');
這種方法不僅比字符串innerHTML 更快,它還允許您將輸入作為JavaScript 對象處理。
input.type = 'button';
input.value = 'edit';
input.onclick = editRecord;
您創建了一個新行,但如果您沒有創建一個新行,您可以清除該行內的代碼:
newRow = (function clearHtmlElement (el){
var newEl = el.cloneNode();
el.parentNode.replaceChild(newEl, el);
return newEl;
}(newRow));
最后將輸入附加到行元素:
newRow.appendChild(input);
然后您就可以使用屬性保存您的值了:
input.dataset.sno = 10;
或者
input.setAttribute('data-sno', 10);
或者您可以將其保存到 HTML 元素中:
input.sno = 10;
function editRecord () {
var sno = this.sno
|| this.getAttribute('data-snow')
|| this.dataset.snow;
...
}
選擇您使用它的方式或像我在這里所做的那樣全部使用它們。 現在您的函數中有sno
可用,更重要的是,它可以是您想要的 JavaScript 對象。
如果您想使用在問題上定義的函數,則必須在定義 onclick 處理程序時執行此技巧:
input.onclick = (function(){
var mySno = sno;
return function(){
editR(mySno);
};
}());
在這里,使用范圍, mySno
將在您每次定義 onclick 處理程序時保存sno
值的引用。 但是這不適用於 objects ,所以只有數字或字符串才能工作......而且它有點難看。
//當sno是整數時
var sno=10;
row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord(" + sno + ");'";
//當sno是一個字符時
var sno='C';
row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord(\\'"+ sno +"\\');'";
editRecord('sno');
正在傳遞字符串“sno”,您需要像這樣傳遞變量: editRecord(sno);
使用我為您寫的以下行:
代碼
var sno=10;
row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord(\'"+sno+"\');'";
永遠不能在雙季銨鹽中使用雙季銨鹽或在單季銨鹽中使用單季銨鹽。 這不是真的。 "xxxxx"yyyyy"xxxx" 可以使用 "xxxxx'yyyyy'xxxxx" 或 "xxxxx\\"yyyyy\\"xxxx" 或 "xxxx"+"yyyyy"+"xxxx"
var sno=10; row.insertCell(6).innerHTML="input type='button' value='edit' onclick='editRecord('+sno+');'";
你已經用這一行傳遞了它: onclick='editRecord(sno);'
只需從 sno 中刪除 '。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.