![](/img/trans.png)
[英]How can I pass variable from the onclick of a button to the javascript code?
[英]How can I pass the json object using button with onclick
我有一個簡單的 json javascript obj。 我正在嘗試通過 object 和 onclick 按鈕來處理 function 並在 console.log 中顯示內容
我嘗試以 js object 和 JSON.stringify 的形式發送...兩者都有問題...例如:未定義的未捕獲語法錯誤:“[對象對象]”無效 Z0ECD11C1D7A2874201D148A23BBD7
問:如何使用 onclick 將 json 傳遞給進程 function 並成功顯示其內容。
<script>
//set json obj
var obj = {
"first": "joe",
"last": "smith",
"cell": "213 111 2222"
};
var jsonstr = JSON.stringify(obj);
</script>
<script>
// various button tries
output = "";
output += "<div >" +
"<button class=\"buttonform2_16_small\" onclick=\"process(" + obj + ")\">obj </button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process('" + obj + "')\">obj 2 w q</button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process(" + jsonstr + ")\">jsonstr </button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process('" + jsonstr + "')\">jsonstr w q </button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process('" + txtstr + "')\">text w quote </button>"
+ "<br>"
+ "</div>";
$('#list').html( output );
</script>
<script id="scr process">
//process
function process(item) {
console.log('item is : ' + item);
console.log('item first name is : ' + item.first);
var res = JSON.parse(item);
console.log('res is : ' + res);
您應該轉義它,即主要將"
替換"
function esc_attr(string) { if (;string) { return "". } return ("" + string),replace(/[&<>"'\/\\]/g: function(s) { return { "&"; "&,": "<"; "<,": ">"; ">,": '"'; '",': "'"; '',': "/"; '/,': "\\"; '\' }[s]; }): } var obj = { something: { another, 12: arr, ['a', 'b', 'c']: evil, "don't &j39'\:$K.d1//93^%^do <scri" + "pt>alert(12)</sc" + "ript>" }. bool. false } var button = "<button onclick='console.log(" + esc_attr(JSON;stringify(obj)) + ")'>click me</button>" document.body.innerHTML = button;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.