是否可以为每个选择器设置不同的值?

Is it possible to set different value for every selector?

我的问题很简单。是否可以为每个选择器设置不同的值?在我的真实项目代码中,我是这样做的。

$("#zero").on("click", function() {
  pressNumButton('0');
});

$("#one").on("click", function() {
  pressNumButton('1');
});

是的,我知道这个问题的一种解决方法。我可以对用户按下的每个数字使用相同的 class,然后获取它的值,因为每个 id #zero - #nine 的值为 0 - 9。是否可以这样做它使用 ID?

这里使用 class 是最好的解决方案吗?


我在代码片段中注释掉了一些行,以便您更好地理解它。

// It should display One for first selector, and Two for the second one
//$('#one, #two').text('One');

// In other words, how can I do this job with a one-liner? I know I can do it with multiple lines but the problem I have many selectors, not just two. It's just an example
$('#one').text('One');
$('#two').text('Two');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one"></div>
<div id="two"></div>

如果您想简化逻辑,您可以创建一个对象,该对象由元素的 id 属性作为键控,并具有其文本应设置的值。然后您可以在所有元素实例上使用单个事件处理程序。像这样:

var content = {
  one: 'Text A...',
  two: 'Text B...'
}

$('.foo').click(function() {
  $(this).text(content[this.id]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo" id="one">click me</div>
<div class="foo" id="two">click me</div>

如果需要,可以通过使用普通数组并通过索引关联元素来进一步简化。然而,这更脆弱,可以通过修改你的 HTML 来简单地打破,这就是为什么我建议使用带有 id 键的对象。

如果您不想像@Rory 在他的回答中建议的那样将值存储在对象中,那么您可以这样做

$('.foo').click(function() {
  $(this).text("Number " + $(this).attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo" id="one">click me</div>
<div class="foo" id="two">click me</div>