简体   繁体   English

如何在jQuery中使用包含“#”的ID选择器?

[英]How I can I use an ID selector that contains a '#' in jQuery?

<div id="content">
<textarea id="#example-1">
</textarea>
<textarea id="#example-2">
</textarea>
</div>

and Jquery 和jQuery

var xyz = $("content##example-1").val();

This code doesn't work for me. 此代码对我不起作用。 It crashes - shows undefined. 它崩溃-显示未定义。 When I delete "#" from div from textarea and one "#" from JS code it works. 当我从textarea的div中删除“#”并且从JS代码中删除一个“#”时,它可以工作。 It need to works with id with "#". 它需要使用带有“#”的id。 Can I put variable into $() after quotation marks? 可以在引号后将变量放入$()吗? Eg: 例如:

$("content#"variable)

Escape the special character in the ID , and remove that content part. 转义ID中的特殊字符 ,然后删除该content部分。 Because element IDs must be unique , an ID selector will match at most one element. 由于元素ID必须唯一 ,因此ID选择器最多可以匹配一个元素。 Therefore, anything beyond that is overspecified. 因此,超出此范围的任何东西都被过度指定。

var xyz = $("#\\#example-1").val();

Better still, don't use a special character in the ID at all: 更好的是,根本不要在ID中使用特殊字符:

<div id="content">
    <textarea id="example-1">
    </textarea>
    <textarea id="example-2">
    </textarea>
</div>
var xyz = $('#example-1').val();

how about $("content#"variable)? $(“ content#” variable)怎么样? Is it possible? 可能吗? Is it exist any possibility to deal with it? 是否有可能解决?

That's not valid JavaScript; 那不是有效的JavaScript; you need to use string concatenation. 您需要使用字符串连接。 Also, the selector 'content' matches elements with tag name content , which is not what you want. 另外,选择器'content'匹配标签名称为content元素,这不是您想要的。 Believe me: just get rid of the content part entirely. 相信我:完全摆脱content部分。

Then use the jq function described in the jQuery FAQ that I linked. 然后使用我链接的jQuery FAQ中描述的jq函数。

var xyz = $(jq(variable)).val();

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

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