jQuery 删除带有非标准 id 字符的表格行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4382832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:10:59  来源:igfitidea点击:

jQuery remove table row with non-standard id characters

jqueryhtml-table

提问by Timothy Ruhle

I am trying to remove a table row using jQuery like this

我正在尝试像这样使用 jQuery 删除表格行

function removeTableRow(trId){
    $('#' + trId).remove();
}

However this doesn't work if the id contains a character like "%", "^", "&", ",", etc....

但是,如果 id 包含“%”、“^”、“&”、“,”等字符,则这不起作用...

Do you know if there is any work around for this?

你知道是否有任何解决方法吗?

采纳答案by Chris Simpson

I believe the reason why can be found here: What are valid values for the id attribute in HTML?

我相信可以在这里找到原因:What are valid values for the id attribute in HTML?

However I'm not so sure about a workaround other than the obvious (change your ids)

但是我不太确定除了明显的解决方法(更改您的 ID)

回答by Tomalak

HTML 4.0 IDs cannot contain these characters and be valid at the same time:

HTML 4.0 ID 不能包含这些字符并且同时有效

Attribute values of type ID and NAME must begin with a letter in the range A-Z or a-z and may be followed by letters (A-Za-z), digits (0-9), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). These values are case-sensitive.

ID 和 NAME 类型的属性值必须以 AZ 或 az 范围内的字母开头,后面可以跟字母 (A-Za-z)、数字 (0-9)、连字符 ("-")、下划线 ("_ ")、冒号 (":") 和句点 (".")。这些值区分大小写。

If you must, you can try this:

如果你必须,你可以试试这个:

function removeTableRow(trId) {
    $(document.getElementById(trId)).remove();
}

I'd recommend fixing the HTML, though.

不过,我建议修复 HTML。

回答by george

I wouldn't suggest using those characters in an id string. However if you feel it necessary then you need to use \\to escape the character in the selector.

我不建议在 id 字符串中使用这些字符。但是,如果您觉得有必要,那么您需要使用\\来转义选择器中的字符。

Example: http://jsfiddle.net/NuWSp/

示例:http: //jsfiddle.net/NuWSp/

<table>
    <tr id="b%b">
        <td>hello</td>
    </tr>
    <tr>
        <td>world</td>
    </tr>
</table>


function removeTableRow(trId){
    $('#' + trId).remove();
}

removeTableRow( "b\%b" );

回答by av_master

It's better if it is several rows in many tables to remove them through another attribute such as class or group.

如果是多个表中的几行,最好通过另一个属性(例如类或组)删除它们。

Here is an example of how to remove via group attribute:

以下是如何通过组属性删除的示例:

$("table tr[group='"+groupname+"']").remove();

I hope this helps.

我希望这有帮助。

回答by grongor

I'm not sure if it will work, but you can try it

我不确定它是否有效,但你可以试试

var id = "id%#&hh";
$("tr").each(function(){
    if($(this).attr("id") == id){
        $(this).remove();
        return;
    }
});