【发布时间】:2019-02-24 04:55:36
【问题描述】:
我正在尝试制作一个可以在单击时编辑 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>
【问题讨论】:
-
你为什么要引用两次:
switchbutton("'block'", "'button1'");? -
你的函数调用有错误。
switchbutton("'block'", "'button1'");应该是switchbutton("block", "button1");。应该是双引号或单引号。两者都不是。 -
那不起作用,我有 2 个引号的原因是因为其中 1 个在传入后会自动删除,并且 DOM 需要元素 id 上的引号。如果你传入单引号,它什么也不做
-
@davej 不正确:这是一个固定的小提琴:jsfiddle.net/togu9drh
-
我明白了,谢谢你的澄清,我想我认为语法更挑剔
标签: javascript html css string dom