javascript Jquery通过'data-id'选择元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23296475/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:41:03  来源:igfitidea点击:

Jquery selecting element by 'data-id'

javascriptjquery

提问by LogixMaster

Similar to the question here, I need to get an element based on its data-id. The problem I encounter is that I want to retrieve a an a element with a certain data-idusing a variable.

类似于这里问题,我需要根据它的data-id. 我遇到的问题是我想data-id使用变量检索具有某个元素的 a 元素。

lets consider the code below:

让我们考虑下面的代码:

var item_id = 12345;

if I want to get the element that has the data-idwith the value of item_id, would I do the following ?

如果我想获取具有data-iditem_id 值的元素,我会执行以下操作吗?

$('[data-id=item_id]')

This does not work, and I am kind of stuck on how I can get around this.

这是行不通的,我对如何解决这个问题有点困惑。

回答by Felix

You can concatenate the variable using +:

您可以使用+以下方法连接变量:

$('[data-id=' + item_id + ']')