javascript - 函数调用中的字符串与函数中定义的字符串不同 - 奇怪的错误
问题描述
我正在尝试制作一个可以在单击时编辑 dom 的函数,我可以将不同的元素传递到该函数中,也可以减少重复代码。但是,当我在函数中将 id 作为字符串传递时,它不会抓取 dom 元素。但是,如果我在函数中声明的字符串中使用相同的文本,它会。我已经尝试控制台记录输出并在 dom 请求中使用我定义的相同字符串,并且该字符串有效,但是函数原型中定义的变量对我来说不是无法解释的。
ex 将起作用 var x = document.getElementById('button1').style.display="block";
但是 var x = document.getElementById(str1).style.display="block"; 不会,其中 str 是从函数头中获取的,即使是 str console.logs("button1"); 但是,如果我在函数 var x = document.getElementById(r).style.display="block"; 中声明了一个变量 r = "button1" - 这将起作用,为什么将字符串传递到函数中以不同方式处理
说明问题的示例小提琴 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>
解决方案
删除“'button1'”周围的单引号。
此功能将起作用:
function switchv(){
switchbutton("block", "button1");
}
编辑:似乎 jsfiddle 不喜欢onclick=switchv()
,尽管在独立的 html 页面中它可以工作。
不过,在 JavaScript 部分中设置 onclick 函数似乎可行。这是修改后的版本:https ://jsfiddle.net/wpvyu5fr/40/
推荐阅读
- ios - ReactNative:如何检查用户是否已授予 gps 权限
- java - 在 Java 项目中查找重复常量
- android - 将 json 传递给包含 json 数组的服务器
- javascript - 使用 .addClass 函数时,边框不会在单击时显示
- firebase - Flutter - 收到firebase通知后重定向
- java - 无法使用 MailService 从 com.google.appengine 库进行 API 调用 mail.Send
- javascript - 如何在后台运行谷歌街景时弹出模式
- powershell - Powershell脚本不适用于附件
- javascript - 我的 Javascript 函数没有设置日期
- rx-java - 初始化后如何更改 rxjava/rxscala 运算符(.debounce)参数