为什么不是我的元素:包含(变量)工作时使用变量而不是字符串? jQuery的

时间:2021-11-22 20:32:43

I have a code to get the value of option element and when a button is clicked, it'll find where that value exist in the page so I can add more things into that table / container.

我有一个代码来获取option元素的值,当单击一个按钮时,它会找到页面中存在该值的位置,这样我就可以在该表/容器中添加更多内容。

Somehow if I store the value into a variable, it doesn't work. If I type in the string directly into $("blah:contains('blabhblah')" it will work. why?

不知何故,如果我将值存储到变量中,它就不起作用。如果我直接输入字符串$(“blah:contains('blabhblah')”它会起作用。为什么?

My example here in html

我的例子是html

        <div class="shipping-time-city">
            <label>City: </label>
            <select>
                <option value='bby'>Burnaby (本拿比)</option>
                <option value='van'>Vancouver (温哥华)</option>
                <option value='rmd'>Coquitlam (高贵林)</option>
            </select>
        </div>

other places in the body I have something like

在身体的其他地方,我有类似的东西

<caption>Coquitlam (高贵林)</caption> <caption>Burnaby (本拿比)</caption> <caption>Vancouver (温哥华)</caption>

Coquitlam(高贵林) Burnaby(本拿比) 温哥华(温哥华)

so in jquery I used click function and this is what I have inside click function

所以在jquery中我使用了click函数,这就是我在click函数里面的内容

var getCity = $( ".shipping-time-city option:selected" ).text();
($("caption:contains(getCity)").text('bye')  //just for testing

the above wouldn't work but if I do it like this

以上情况不会奏效,但如果我这样做的话

($("caption:contains('Burnaby (本拿比)')").text('bye')

it will work, but I tried console.log(getCity) which gives me the output of Burnaby (本拿比)

它会工作,但我尝试了console.log(getCity),它给了我Burnaby的输出(本拿比)

can someone give me a hand on what I am doing wrong here?

有人可以帮我解决我在这里做错了什么吗?

Thanks a lot.

非常感谢。

1 个解决方案

#1


1  

since getCity is a variable, would it not be:

因为getCity是一个变量,它不会是:

($("caption:contains('" + getCity + "')").text("bye");

#1


1  

since getCity is a variable, would it not be:

因为getCity是一个变量,它不会是:

($("caption:contains('" + getCity + "')").text("bye");