2017-06-14 62 views
-1

我有三个的div,每个具有一个onclick(一个b,和Ç)。我希望每个发送一个唯一的值返回到一个全局变量X(例如一个使得X = 1,b使得X = 2,等等)。我一度获得了一些小小的成功,但现在看起来代码只是从上到下运行,忽略了其他功能,并且简单地使x等于最后一个函数的更新值,c更新全局变量在具有一个多Onclicks的

HTML:

<div id='testChoice'>Choose action</div> 
<div id='a'>a</div> 
<div id='b'>b</div> 
<div id='c'>c</div> 

JS:

var x = ""; 

function aChoice() { 
    this.x = "a"; 
} 

function bChoice() { 
    x = "b"; 
} 

function cChoice() { 
    x = "c"; 
} 

document.getElementById("a").onclick = aChoice(); 
document.getElementById("b").onclick = bChoice(); 
document.getElementById("c").onclick = cChoice(); 

document.getElementById("testChoice").innerHTML = x; 

可变X(它只是显示在HTML用于测试)是我想更新的东西。它将被更改为一个int值以用于其他函数。这个想法是,用户的选择将更新然后传递给其他功能的变量。现在,x总是作为c出现,并且没有识别出onclick。

谢谢你的帮助!

+1

最后一行是不会神奇地运行X更新的时候....你正在调用这些方法.... – epascarello

回答

0

你重复了很多代码。这将是一个简单的方法来实现你想要的。

var x = ""; 
 

 
function choice(value) { 
 
    x = value; 
 
    document.getElementById("testChoice").innerHTML = value; 
 
} 
 

 
document.getElementById("a").onclick = choice.bind(null, "a") 
 
document.getElementById("b").onclick = choice.bind(null, "b") 
 
document.getElementById("c").onclick = choice.bind(null, "c")
<div id='testChoice'>Choose action</div> 
 
<div id='a'>a</div> 
 
<div id='b'>b</div> 
 
<div id='c'>c</div>

而且,当前的代码总是显示c,因为你的最后一行只执行一次。并且最后一次x被分配一个值是当你说cChoice()

0

这个将帮助你。对于OnClick你应该只提供函数名称。 aChoice()实际上会在添加onclick侦听器时调用。您得到的是最后一个函数输出,因为cChoice是按顺序执行的最后一个函数。

var x = ""; 
 

 
function aChoice() { 
 
    x = "a"; 
 
    document.getElementById("testChoice").innerHTML = x; 
 
} 
 

 
function bChoice() { 
 
    x = "b"; 
 
    document.getElementById("testChoice").innerHTML = x; 
 
} 
 

 
function cChoice() { 
 
    x = "c"; 
 
    document.getElementById("testChoice").innerHTML = x; 
 
} 
 

 
document.getElementById("a").onclick = aChoice; 
 
document.getElementById("b").onclick = bChoice; 
 
document.getElementById("c").onclick = cChoice;
<div id='testChoice'>Choose action</div> 
 
<div id='a'>a</div> 
 
<div id='b'>b</div> 
 
<div id='c'>c</div>

0

随着let或方式关闭可以是一个很好的解决

\t var test = document.querySelectorAll(".test"); 
 
\t for (let i = 0; i < test.length; i++) { 
 
\t \t test[i].onclick = function() { 
 
\t \t \t document.getElementById("testChoice").innerHTML = test[i].innerHTML; 
 
\t \t } 
 
\t }
<div id='testChoice'>Choose action</div> 
 
<div class="test">a</div> 
 
<div class="test">b</div> 
 
<div class="test">c</div>