使用转义字符将变量作为参数发送不起作用

时间:2017-04-06 15:17:44

标签: javascript arguments

发送变量作为参数在此代码中不起作用



document.write('<input type="text" id="argument">');
var testArg = document.getElementById('argument').value;
document.write('<button onclick="sendArg(\'' + testArg + '\')">Display Argument</button>');
document.write('<p id="displayArg"></p>')

function sendArg(recArg) {
  document.getElementById('displayArg').innerHTML = recArg;
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您在编写testArg元素后立即为input变量指定值。由于没有value属性,因此其值为空字符串。

如果要在单击按钮时获取值 ,则需要在处理按钮单击的事件处理程序中从DOM中读取它。

您也应该避免使用document.write。除了擦除现有文档的副作用之外,尝试手动转义HTML和JS的字符串是很痛苦的(如果用户在输入中写了"'会怎样?这会打破你的HTML试图产生)。

var p = document.createElement("p");
var inp = document.createElement("input");
var bt = document.createElement("button");
bt.appendChild(document.createTextNode("Display Argument"));
bt.type = "button";
bt.addEventListener("click", sendArg);

function sendArg(event) {
  p.innerHTML = inp.value;
}

document.body.appendChild(inp);
document.body.appendChild(bt);
document.body.appendChild(p);

答案 1 :(得分:-1)

您使用单引号打开HTML属性,不能将其用作JavaScript字符串,因为您将关闭HTML属性,请使用双引号:

document.write("<button onclick="sendArg(\''+testArg+'\)">Display Argument</button>");