简体   繁体   English

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

[英]getting updated variable value from function jquery

I made this as simple as I could 我尽可能简单地做到了这一点

Here is my HTML code: 这是我的HTML代码:

    <div id="outsideCounter"><p></p></div>

    <div id="clickToAdd"><p>Click me</p></div>

    <div id="insideCounter"><p></p></div>

And here is the javascript: 这是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
        });

});

Now the problem is that when you click 'clickToAdd' it adds 1 only to the insideCounter . 现在问题是当你点击'clickToAdd'时它只向insideCounter添加1。 How could I get that same updated level to the outsideCounter ? 我如何才能获得与outsideCounter相同的更新级别? I've been struggling with this for hours now and my brains are so jammed I can't figure this out on my own. 我已经为此苦苦挣扎了好几个小时,而且我的大脑非常拥挤,无法独自解决。

I have been exercising javascript only for a week now so please try to keep it as simple as possible because I couldn't even find anything useful from the previous answers about 'getting variable from function'. 我现在只锻炼了一个星期的JavaScript,所以请尽量保持简单,因为我甚至找不到任何有用的关于'从函数中获取变量'的答案。

I made jsfiddle if that helps to understand my problem. 如果这有助于理解我的问题,我制作了jsfiddle

您可以用逗号分隔选择器,但由于两个ID都以Counter结尾,因此您可以通过组合使用属性选择器的结尾来使用该模式。

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

Simply add outsideCounter > p to your selector: 只需将outsideCounter > p添加到选择器中即可:

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

Fiddle 小提琴

$(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