简体   繁体   English

jquery'属性包含'具有动态值的选择器

[英]jquery 'attribute contains' selector with a dynamic value

Let's say that i have a variable questionId which is an integer, and i want to find tr elements that have the fragment ( "question_"+questionId ) in their id. 假设我有一个变量questionId是一个整数,我想在他们的id中找到包含片段( "question_"+questionId )的tr元素。 How can i do this? 我怎样才能做到这一点? I thought that i would be able to do it with the jquery 'attribute contains' selector . 我以为我可以用jquery '属性包含'选择器来做到这一点。

Eg, this works, for a non-dynamic value, 例如,这适用于非动态值,

$("tr[id*='quiz_question_7674']")

but, i can't work out how to plug the variable value in there. 但是,我无法弄清楚如何在那里插入变量值。 This doesn't work for example: 这不适用于例如:

questionId = 7674;
$("tr[id*='quiz_question_'+questionId]")

Any ideas anyone? 任何人的想法? Is there a better way than 'attribute contains' to do it? 有没有比“属性包含”更好的方法来做到这一点? I have the feeling i'm missing something obvious. 我感觉我错过了一些明显的东西。

thanks, max 谢谢,最大

EDIT - SOLVED. 编辑 - 已解决。 doh, i am indeed missing something obvious. 啊,我确实错过了一些明显的东西。 I keep forgetting that it's just a string, nothing more: 我一直忘记它只是一个字符串,仅此而已:

$("tr[id*='quiz_question_"+questionId+"']") $( “TR [ID * = 'quiz_question _ ”+ questionId +“']”)

You have error: 你有错误:

var questionId = 7674;
$("tr[id*='quiz_question_" + questionId + "']");

Notes: 笔记:

  1. Please use var to declare variables. 请使用var来声明变量。
  2. questionId is a variable. questionId是一个变量。 It is not part of the selector. 它不是选择器的一部分。 You should concatenate questionId to the string. 你应该将questionId连接到字符串。

Yep, you almost had it: 是的,你几乎拥有它:

var selector = "tr[id*='quiz_question_" + questionId + "']";
$(selector)

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

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