简体   繁体   中英

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

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

$("content#"variable)

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();

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();

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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