gpt4 book ai didi

javascript - 在 jQuery 选择器中连接

转载 作者:行者123 更新时间:2023-11-29 17:56:09 24 4
gpt4 key购买 nike

简单的问题。我有一个 js 变量,我也想在 jQuery 选择器中连接起来。但是它不起作用。也没有错误弹出。怎么了?如何正确地将变量连接到 jQuery 选择器中的某些文本。

<select class="form-control" name="taille"  id="{{Product.id~'/taille'}}">
<option>Taille</option>
<option>1</option>
<option>2</option>
</select>

并在 jquery 中使用此代码获取所选选择的 id

$('select[name="taille"]').focusin(function(){ 
var idElement = $(this).attr('id');
var arr = idElement.split('/');

它的工作非常好,但问题是我想通过 id 为选定的选择附加选项我尝试了很多代码,但没有人可以作为例子:

$('#'+arr[0]+'/taille')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;

请帮忙,谢谢。

最佳答案

使用 attribute equals selector

$('[id="' + arr[0] + '/taille"]')


或者您需要使用 / 转义元字符 ( \\ ) .

$('#' + arr[0] + '\\/taille')

检查 documentation of jQuery selectors :

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^``{|}~) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.


我认为您正在尝试使用自己的 id 来获取相同的元素.如果yes那么就不需要那个用途this引用相同的元素。虽然不需要删除并再次添加,但只需使用 html() 这将删除现有的。

$('select[name="taille"]').focusin(function(){ 
$(this).html('<option value="whatever" selected>text</option>');
});

关于javascript - 在 jQuery 选择器中连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38916447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com