[英]Javascript Help for Innerhtml
我一直在尝试下面的Javascript代码,该代码将允许我根据单击的内容将不同的变量插入html。 不幸的是,它不会显示变量的值,而只会显示如下定义的变量名称。
<head>
<script type="text/javascript">
var data=new String ()
data="This is what I want to Show"
function myFunction(text)
{
elem = document.getElementById('replace');
elem.innerHTML = text
}
</script>
</head>
<body>
<button onclick="myFunction('data')"> Press </button>
<div id="replace">
Test
</div>
</body>
您要传递字符串,而不是变量,请使用:
onclick="myFunction(data)"
字符串必须用引号引起来,变量(在这种情况下是对字符串的引用)一定不能用引号引起来(否则它将被视为文字字符串)。
顺便说一句,JavaScript不需要您在为字符串分配值之前显式创建一个字符串,您可以只使用:
var data = 'This is what I want to show.';
在使用innerHTML
同时,如果您要做的只是更新文本内容(并且不考虑嵌套节点),则可以简单地使用:
function myFunction(text) {
// the var declaration prevents the variable becoming global
var elem = document.getElementById('replace');
elem.appendChild(document.createTextNode(text));
}
为了使其更通用,请避免在功能中硬编码要更改的元素的id
,而应将其传递给函数:
function myFunction(text, elem) {
// testing if the element is a node, if not assume it's a string of the id:
var elem = elem.nodeType === 1 ? elem : document.getElementById('replace');
elem.appendChild(document.createTextNode(text));
}
并将以上内容与:
onclick="myFunction(data, 'replace')"
要么:
onclick="myFunction(data, document.getElementById('replace'))"
我也强烈建议不要使用内联/侵入式JavaScript,而只是为了使其更容易在一个地方更新要调用的函数,参数和函数本身(而不是必须浏览文档和查找调用该函数的每个实例):
// define the function here
var buttons = document.getElementsByTagName('button'),
replace = document.getElementById('replace'),
data = 'Text I want to show.';
for (var i = 0, len = buttons.length; i < len; i++){
buttons[i].onclick = function(){
myFunction(data, replace);
};
}
data
附加到全局window
对象。 要访问它:
elem.innerHTML = window[text];
另外,不需要new String()
作为字符串,可以通过以下方式定义:
var data = "This is what I want to Show";
如果“这就是要显示的内容”,最好将其放在参数中,以便在有更多按钮的情况下可以重用该函数:
<button onclick="myFunction('This is what I want to Show')">Press</button>
参见DEMO 。
这是您的代码。
<button onclick="myFunction('data')"> Press </button>
因为这里是一个字符串,而不是引用对象“数据”。所以我想这就是您想要的。
1。
<button onclick="myFunction(data)"> Press </button>
2. <button onclick="myFunction('This is what I want to Show')"> Press </button>
您正在使用变量文本来分配值,以使用ID替换进行潜水。 用这个。
elem.innerHTML = data instead elem.innerHTML = text.
或将args传递给功能而无需单个qoute。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.