我尽可能简单地做到了这一点
这是我的 HTML 代码:
<div id="outsideCounter"><p></p></div>
<div id="clickToAdd"><p>Click me</p></div>
<div id="insideCounter"><p></p></div>
这是 JavaScript:
$(document).ready(function(){
var level = 1; // start the counting at 1
$('#outsideCounter > p').html(level); // show value of the first counter
$('#clickToAdd').click(function(){
level++; // I want this to add both counters, not just the insideCounter
$('#insideCounter > p').html(level); // show value of the second counter
});
});
现在的问题是,当您单击“clickToAdd”时,它只会向 insideCounter 添加 1。我怎样才能让 outsideCounter 获得相同的更新级别?我已经为此苦苦挣扎了好几个小时,我的大脑已经被卡住了,我无法自己解决这个问题。
我现在只练习了 javascript 一周,所以请尽量保持简单,因为我什至无法从之前关于“从函数获取变量”的答案中找到任何有用的东西。
我做了jsfiddle如果这有助于理解我的问题。
最佳答案
您可以用逗号 ,
分隔选择器,但由于两个 id 都以 Counter
结尾,因此您可以通过组合 ends- 来使用该模式with 与属性选择器一起使用。
$('[id$=Counter] > p').html(level);
关于javascript - 从函数 jquery 获取更新的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28479468/