html中寫js代碼:
正常寫法(一般情況下):
<input value="" type="button" οnclick="alert('OK');" />
其實更好的寫法:
<input value="Test" type="button" οnclick="alert("OK");" />
因爲此時仍是在html管轄範圍內的,所以"會被解析爲雙引號
js中寫html代碼:
function addarow(){
var trnum = $("#table_1_id tr").length;
var trid ="n"+trnum;
var tr="<tr id="+trid+"><td><input type='button' οnclick='console.log('"+trid+"')' value='查看該行id'></td></tr>";
$("#table_1_id").append(tr);
}
這點代碼相信大家也都看得懂.
在table中新加一行該行id爲 字母n加上總行數 如 n1 (n可以用來區分是否是新加的行)
然後添加一個按鈕,點擊時在控制檯打印出該新行的id
但是這樣寫是不對的!!!會報Uncaught SyntaxError: Unexpected token } 的錯誤
是因爲onclick事件是 console.log( 只能解析到第二個單引號號並把它作爲結束標誌
如果寫成
var tr="<tr id="+trid+"><td><input type='button' οnclick='console.log("+trid+")' value='查看該行id'></td></tr>";
能不能達到想要的效果呢?試下就知道了 結果爲:我就不打了直接貼圖吧
但是我真的想獲取新行id該如何處理?總會有解決辦法的
var tr="<tr id="+trid+"><td><input type='button' οnclick='console.log(""+trid+"")' value='查看該行id'></td></tr>";
這樣就可以了因爲新行添加到html後其實就是上面那張圖的內容,如果加了"的話就會變成 console.log("n1") 被html解析爲 console.log("n1")這樣就可以正常獲取新行的id了。
還有一種方法就是外部不使用引號
var tr="<tr id="+trid+"><td><input type='button' οnclick=console.log('"+trid+"') value='查看該行id'></td></tr>";