繁体   English   中英

编写一个能够跟踪按钮点击的功能

[英]Writing a Function that will Keep Track of Button Clicks

我试图在按钮上显示用户点击按钮的次数。 我想这样做而不为每个按钮写一个单独的功能,因为我打算有很多按钮。

<button class="itemButton"> Button A <span class="itemCount"> 0 </span> </button>
<button class="itemButton"> Button B <span class="itemCount"> 0 </span> </button>
<button class="itemButton"> Button C <span class="itemCount"> 0 </span> </button>

我的方法是尝试通过按钮上的itemCount类访问span,增加“items”对象中该按钮的timesClicked属性,然后将span的文本设置为该值。

var items = {
    "Button A": {
        timesClicked: 0
    }
    "Button B": {
        timesClicked: 0
    }
    "Button C": {
        timesClicked: 0
    }
}

$('.itemButton').click(function () {
    var itemName = $(this).text();
    items.itemName.timesClicked++;
    $(this).children(".itemCount") = items.itemName.timesClicked;

});

我已经阅读了一些关于跟踪按钮点击的其他问题,但没有找到任何完全解决这种情况的问题。 我花了一些时间筛选Jquery API并使用了许多不同的函数,所以我很可能采取了一种完全不正确的方法。 感谢您提供的任何指导。

首先,您可以使用data属性更可靠地识别按钮:

<button class="itemButton" data-button="A">
    Button A 
    <span class="itemCount">0</span> 
</button>
<button class="itemButton" data-button="B">
    Button B 
    <span class="itemCount">0</span> 
</button>
<button class="itemButton" data-button="C">
    Button C 
    <span class="itemCount">0</span> 
</button>

然后,您可以使用它来标识对象中的每个项目。 注意,在使用变量访问对象属性时,需要使用数组索引表示法,并且对象语法也不正确。

var items = {
    "A": { timesClicked: 0 },
    "B": { timesClicked: 0 },
    "C": { timesClicked: 0 }
}
$('.itemButton').click(function () {
    var button = $(this).data('button');
    items[button].timesClicked++;
    $(this).children(".itemCount").text(items[button].timesClicked);
});

示例小提琴

如果要通过变量获取对象的属性,则应使用括号:

items[itemName].timesClicked

在您的情况下,您实际上正在寻找items变量的名为itemName的属性。

演示: 在提琴手中

首先,您错过了items逗号分隔符 - 变量。 此外,按钮中的文本是您输入的文本+点击次数(但items键 - 变量只是计数前的文本,因此items.itemText将始终未定义。最好的方法是添加按钮的ID并添加这些ID作为items中的键 - 变量。检查我的示例它非常简单并且可以按照您的需要工作。

HTML:

<button class="itemButton" id="btnA"> Button A <span class="itemCount"> 0 </span>     </button>
<button class="itemButton" id="btnB"> Button B <span class="itemCount"> 0 </span> </button>
<button class="itemButton" id="btnC"> Button C <span class="itemCount"> 0 </span> </button>

使用Javascript:

var items = {
 "btnA": {
    timesClicked: 0
 },
 "btnB": {
    timesClicked: 0
 },
 "btnC": {
     timesClicked: 0
 },
};

$('.itemButton').click(function () {
    var itemId = this.id;
    if(items[itemId] != undefined){
    items[itemId].timesClicked++;
    $(this).children(".itemCount").html(items[itemId].timesClicked);
    }
});

希望这对你有所帮助。

暂无
暂无

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

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