我有以下JS正在工作,但我很困惑为什么我需要将变量func包装在引号中。有人可以解释一下吗?
function CustomPrompt(){
this.render = function(dialog,func){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = ' ';
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxbody').innerHTML += '<br><input id="prompt_value1" >';
document.getElementById('prompt_value1').focus();
//HERE'S THE LINE I'M CONFUSED BY
//*******************************
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Prompt.ok(\''+func+'\')">OK</button> <button onclick="Prompt.cancel()">Cancel</button>';
}
this.cancel = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
this.ok = function(func){
var prompt_value1 = document.getElementById('prompt_value1').value;
window[func](prompt_value1);
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
答案 0 :(得分:1)
func
变量似乎是一个字符串,用于标识您在window
函数中使用window[func](prompt_value1);
调用的全局ok
对象附加的函数。
func
需要作为字符串发送,因为它是窗口对象上的键。
如果您要删除示例中的qoutes按钮的onclick方法将尝试在当前范围内发送func
变量的值。由于在您的函数范围中声明func
,您将无法访问它。相反,变量值是内联的。
此示例内联变量 place
function hello(place) {
console.log(place);
}
function iHaveMyOwnScope() {
var place = "world"; // this is in my scope
var container = document.getElementById('container1');
container.innerHTML = '<button onclick="hello(\''+place+'\')">Hello1</button>';
}
iHaveMyOwnScope();
&#13;
<div id="container1"></div>
&#13;
此示例尝试通过全局范围访问变量 place
由于place
未在全局范围内定义,因此无法访问。
function hello(place) {
console.log(place);
}
function iHaveMyOwnScope() {
var place = "world"; // this is in my scope
var container = document.getElementById('container1');
container.innerHTML = '<button onclick="hello(place)">Hello2</button>';
}
iHaveMyOwnScope();
&#13;
<div id="container1"></div>
&#13;
此示例以编程方式创建按钮并将事件处理程序附加到函数范围内
function hello(place) {
console.log(place);
}
function iHaveMyOwnScope() {
var place = "world"; // this is in my scope
var container = document.getElementById('container1');
var button = document.createElement('button')
button.innerHTML = 'Hello3'
button.addEventListener('click', function() {
// Here we can access the place variable
// since this handler is defined in the functions scope
hello(place)
}, false)
// Add button to container
container.appendChild(button);
}
iHaveMyOwnScope();
&#13;
<div id="container1"></div>
&#13;