如何在jQuery中使用包含“#"的ID选择器? [英] How I can I use an ID selector that contains a '#' in jQuery?

查看:347
本文介绍了如何在jQuery中使用包含“#"的ID选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

和Jquery

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

此代码对我不起作用.它崩溃-显示未定义.当我从textarea的div中删除#"并且从JS代码中删除一个#"时,它可以工作.它需要与带有#"的id一起使用. 可以在引号后将变量放入$()吗?例如:

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. It need to works with id with "#". Can I put variable into $() after quotation marks? E.g.:

$("content#"variable)

推荐答案

在特殊字符中转义ID ,然后删除该content部分.因为元素ID必须唯一,所以ID选择器将最多匹配一个 个元素.因此,超出此范围的任何东西都被夸大了.

Escape the special character in the ID, and remove that content part. Because element IDs must be unique, an ID selector will match at most one element. Therefore, anything beyond that is overspecified.

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

更好的是,完全不要在ID中使用特殊字符:

Better still, don't use a special character in the ID at all:

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

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


$("content#" variable)怎么样?是否有可能?有可能解决吗?

how about $("content#"variable)? Is it possible? Is it exist any possibility to deal with it?

那不是有效的JavaScript;您需要使用字符串连接.另外,选择器'content'匹配标签名称为content的元素,这不是您想要的.相信我:完全摆脱content部分.

That's not valid JavaScript; you need to use string concatenation. Also, the selector 'content' matches elements with tag name content, which is not what you want. Believe me: just get rid of the content part entirely.

然后使用我链接的jQuery FAQ中描述的jq函数.

Then use the jq function described in the jQuery FAQ that I linked.

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

这篇关于如何在jQuery中使用包含“#"的ID选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆