在 jQuery 中通过部分 ID 查找元素?

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

Find an element by partial ID in jQuery?

jquery

提问by Ian Boyd

I have an element on my page, where i only will know part of its id, e.g. _moComments_:

我的页面上有一个元素,我只知道其中的一部分id,例如_moComments_

id="MainContent_listSelectedDays_listDayBanks_0_moComments_0"

How can i find an element by partial id (e.g. using jQuery)?

如何通过部分 id 找到元素(例如使用 jQuery)?

For example (jsFiddle):

例如(jsFiddle)

<input type="text" id="MainContent_listSelectedDays_listDayBanks_0_moComments_0">

with script

带脚本

$('[id=_moComments_]').val("Found it");

Bonus Reading

奖励阅读

回答by zzzzBov

You could use the "Attribute Contains Selector":

您可以使用“属性包含选择器”

$('[id*="_moComments_"]')

However you'd probably be better off by simply adding a class or a custom [data-*]attribute and selecting based on that.

但是,通过简单地添加类或自定义[data-*]属性并基于此进行选择,您可能会更好。