[英]Removing HTML elements with special characters
I want to remove HTML DOM object by its ID, that contains special characters(dots, commas etc).我想通过其 ID 删除 HTML DOM 对象,其中包含特殊字符(点、逗号等)。 I tried to use this code that escapes those characters but it's not working (element its not being removed):
我尝试使用此代码来转义这些字符,但它不起作用(元素未被删除):
var file_html_id ="#"+ filename.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, "\\\\$&");
console.log(file_html_id);
$(file_html_id).remove();
where filename its the ID.其中文件名是 ID。 It's worth to mention that string with escaped characters is displayed as expected.
值得一提的是,带有转义字符的字符串按预期显示。 And if I "hardcode" that string it works fine... So where the problem might be?
如果我“硬编码”该字符串它工作正常......那么问题可能出在哪里?
Instead of trying to escape the characters yourself you could try a couple of other ways:您可以尝试其他几种方法,而不是尝试自己转义字符:
Use jQuery's escapeSelector() on the id string.在 id 字符串上使用jQuery 的 escapeSelector() 。 This will escape any special characters in the string.
这将转义字符串中的任何特殊字符。 Note
escapeSelector
was added in v3.0 of jQuery.注意
escapeSelector
是在jQuery v3.0 中添加的。 View how they are doing the escaping here if interested.如果有兴趣,请查看他们如何在此处进行转义。
$( '#'+ $.escapeSelector('theText') )
Use an attribute selector instead of trying to escape all the possible characters for an id selector使用属性选择器而不是尝试为 id 选择器转义所有可能的字符
$('[id="idHere"]')
This however will select multiple elements if for some bizarre reason you have multiple elements with the same id.但是,如果出于某种奇怪的原因您有多个具有相同 id 的元素,这将选择多个元素。
Demo演示
var id = "some,weird®,id"; var id2 = "some,other®,id"; $('#'+ $.escapeSelector(id2) ).css({border:'1px solid green'}); $('[id="'+id+'"]').css({border:'1px solid red'});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <div id="some,weird®,id"></div> <br/> <div id="some,other®,id"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.