簡體   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