我正在尝试创建一个可在单击时编辑dom的函数,以便可以将不同的元素传递到其中,也可以减少重复的代码。但是,当我在函数中将ID作为字符串传递时,它将不会获取dom元素。但是,如果我在函数中声明的字符串中使用相同的文本,则它将。我已经尝试过控制台记录输出,并在dom请求中使用由我定义的相同字符串,但是该方法可以正常工作,但是在函数原型中定义的变量对我来说似乎无法解释。
e.x可以工作var x = document.getElementById('button1')。style.display =“ block”;
但是var x = document.getElementById(str1).style.display =“ block”;从函数头获取str的地方,即使是str console.logs(“ button1”);也不会。 但是,如果我在函数内声明变量r =“ button1” var x = document.getElementById(r).style.display =“ block”; -这会起作用 为什么将字符串传递给函数的方式不同
示例小提琴说明了问题 https://jsfiddle.net/peacefulgoldfish/wpvyu5fr/20/
html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
type="text/javascript"
src="/js/lib/dummy.js"
></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
#div1 {
width: 100px;
height: 30px;
background-color: red;
}
#button1{
display: none;
width: 100px;
height: 30px;
background-color:blue;
}
</style>
<!-- TODO: Missing CoffeeScript 2 -->
<script type="text/javascript">
function switchv(){
switchbutton("'block'", "'button1'");
}
function switchbutton(str, str2){
console.log(str2)
r = str2;
var x = document.getElementById(r).style.display="block";
}
</script>
</head>
<body>
<button id="div1" onclick="switchv();">
</button>
<div id="button1">
</div>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: ""
}], "*")
}
</script>
</body>
</html>
答案 0 :(得分:1)
删除“'buttton1'”周围的单引号。
此功能将起作用:
function switchv(){
switchbutton("block", "button1");
}
编辑:尽管在独立的html页面中它可以工作,但jsfiddle似乎不喜欢onclick=switchv()
。
但是,在JavaScript部分中设置onclick函数似乎可行。这是修改后的版本:https://jsfiddle.net/wpvyu5fr/40/
答案 1 :(得分:0)
断开与您发送的小提琴的链接,似乎您在switchbutton函数str1中调用了str参数,它们必须相同。同样,双引号也没有必要。
function switchbutton(str, str2){
var x = document.getElementById(str2);
x.style.display = str;
}