繁体   English   中英

从函数jquery获取更新的变量值

[英]getting updated variable value from function jquery

我尽可能简单地做到了这一点

这是我的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结尾,因此您可以通过组合使用属性选择器的结尾来使用该模式。

$('[id$=Counter] > p').html(level);

只需将outsideCounter > p添加到选择器中即可:

$('#insideCounter > p, #outsideCounter > p').html(level);

小提琴

$(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, #outsideCounter > p').html(level); // show value of the second counter
        });

});
$(document).ready(function () {

var level = 1; // same variable for both counter

$('#outsideCounter > p').html(level); // show first counter

$('#clickToAdd').click(function () {
    level++; // this only adds insideCounter
    $('#insideCounter > p, #outsideCounter > p').html(level);
  }); 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM