function dowork()
{
$(".wrappedElement").removeClass("wrappedElement");
$(".wrappedElementout").removeClass("wrappedElementout");
var a=$("div#DepPart select option:selected").val();
$("div#TestPart select option[value^=a]").addClass("wrappedElement");
$("div#TestPart select option[value!=a]:not(div#TestPart select option[value^=a])").addClass("wrappedElementout");
}
在这个函数中,var a以字符串格式获取值(a =“HMT”),当我将此值用作jQuery选择器的一部分时,由于某种原因它不起作用。任何人都可以提出解决方案的建议吗?
答案 0 :(得分:2)
问题是您没有在任何地方引用变量a
,只是在字符串中包含字母“a”。您需要将变量a
中的值与您用作选择器的字符串连接起来:
$("div#TestPart select option[value^='" + a + "']").addClass("wrappedElement");
$("div#TestPart select option[value!='" + a + "']:not(div#TestPart select option[value^='" + a + "'])").addClass("wrappedElementout");
另请注意,方括号属性等于某些语法的jQuery选择器需要某些引号(我上面已包含)。
使用您的示例值a
,“HMT”,第一个选择器在连接后最终将如下所示:
"div#TestPart select option[value^='HMT']"
(与另一行相似。)
答案 1 :(得分:1)
function dowork()
{
$(".wrappedElement").removeClass("wrappedElement");
$(".wrappedElementout").removeClass("wrappedElementout");
var a=$("div#DepPart select option:selected").val();
$("div#TestPart select option[value^=" + a + "]").addClass("wrappedElement");
$("div#TestPart select option[value!=" + a + "]:not(div#TestPart select option[value^="+ a + "])").addClass("wrappedElementout");
}
答案 2 :(得分:0)
您使用a
作为字符串文字的一部分,即它被解释为字符“a”,而不是变量a
的值。
您需要从双引号中取出a
:
$("div#TestPart select option[value^=" + a + "]").addClass("wrappedElement");
$("div#TestPart select option[value!=" + a + "]:not(div#TestPart select option[value^=" + a + "])").addClass("wrappedElementout");