jQuery 单个 JavaScript 单击事件中的多个 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18508742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple id's in a single JavaScript click event
提问by MAR
In JavaScript I am using click event to change chart data. Below is a method for click event.
在 JavaScript 中,我使用 click 事件来更改图表数据。下面是一个点击事件的方法。
$('#pro1').click(function () {
chart.series[0].update({
data: pro1
});
});
$('#pro2').click(function () {
chart.series[0].update({
data: pro2
});
});
$('#pro3').click(function () {
chart.series[0].update({
data: pro3
});
});
I need to minify these three click events in one event, means I want to write one click event which handle the id's. some thing like below code.
我需要在一个事件中缩小这三个点击事件,这意味着我想编写一个处理 id 的点击事件。类似于下面的代码。
$('#pro'+i).click(function () {
chart.series[0].update({
data: pro+i
});
});
I don't know how to do it exactly. The above code is not correct, it is just my lack of knowledge of JavaScript.
我不知道该怎么做。上面的代码是不正确的,只是我对 JavaScript 的了解不足。
采纳答案by undefined
I would suggest creating an object and selecting the elements using classes, id
of the clicked element retrieves value of the corresponding property of the helper object:
我建议创建一个对象并使用类选择元素,id
单击的元素会检索助手对象的相应属性的值:
var pros = {
pro1: '...',
pro2: '...'
};
$('.pros').click(function () {
chart.series[0].update({
data: pros[this.id]
});
});
回答by Alex K
Try this:
尝试这个:
var that = this;
$('#pro1,#pro2,#pro3').click(function () {
chart.series[0].update({
data: that[$(this).attr('id')];
});
});
回答by Tushar Gupta - curioustushar
$('#pro1,#pro2,#pro3').click(function () {
chart.series[0].update({
data: $(this).attr('id');
});
});
Updated code
更新代码
$('#pro1,#pro2,#pro3').click(function () {
chart.series[0].update({
data: window[this.id]
});
});
回答by Niall Paterson
Use a class.
使用一个类。
$('.pro').click(function () {
chart.series[0].update({
data: $(this).attr('id');
});
});
And then on each of the #pro1, #pro2, #pro3 elements add a class of 'pro'
然后在每个#pro1、#pro2、#pro3 元素上添加一个“pro”类
回答by Grigur
$("*[id^=pro]").click(function () {
chart.series[0].update({
data: $(this).attr('id');
});
});
回答by Dominic Sore
You could give all of your elements a class name and use the :eq() selector within jQuery.
您可以为所有元素指定一个类名,并在 jQuery 中使用 :eq() 选择器。