Javascript 无法对文档执行查询选择器,id 不是有效的选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34777481/
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-23 16:50:06  来源:igfitidea点击:

Failed to execute query selector on document, id is not a valid selector

javascripthtmlcss

提问by

I'm trying to create a way to edit a bunch of comments and identify them by some id that I can generate. The errors I'm having is that there is:

我正在尝试创建一种方法来编辑一堆评论并通过我可以生成的一些 ID 来识别它们。我遇到的错误是:

SyntaxError: Failed to execute 'querySelector' on 'Document': '#1234' is not a valid selector. However, I don't see how this is possible since I clearly have id=1234in the <p>.

语法错误:无法在“文档”上执行“querySelector”:“#1234”不是有效的选择器。但是,我不明白这是怎么可能的,因为我显然id=1234<p>.

Additionally, there are issues where when I comment everything else and do an alert(id), this does not work for the second form and the error is that:

此外,还有一些问题,当我评论其他所有内容并执行 alert(id) 时,这不适用于第二种形式,错误是:

TypeError: Cannot read property 'classList' of null.

类型错误:无法读取 null 的属性“classList”。

Here is it in jfiddle: https://jsfiddle.net/wafqgq0L/2/

这是 jfiddle:https://jsfiddle.net/wafqgq0L/2/

document.querySelector('.editable').addEventListener('click', function(event) {
 var index = event.target.id.indexOf('_');

 var id = event.target.id.substring(0,index);
 
 //actual data
 document.querySelector('#'+id).classList.add('hidden');
  
  //edit button
  document.querySelector("#"+id+"_edit").classList.add('hidden');
  
  //textarea
 document.querySelector("#"+id+"_editable").classList.remove('hidden');
  
  //save button
 document.querySelector("#"+id+"_save").classList.remove('hidden');

});
.hidden {
  display: none;
}
//all id will be like 12345_comment

<div class="editable">
<p id="1234">
  Some comment
</p>

<form action="form.php" method="post">
  <textarea id="1234_editable" class="hidden">Some comment</textarea>
  <a href="#" id="1234_edit">Edit</a>
  <a href="#" id="1234_save" class="hidden">Save</a>
</form>
</div>
<br><br>
<div class="editable">
<p id="123">
  Some comment
</p>

<form class="editable" action="form.php" method="post">
  <textarea id="123_editable" class="hidden">Some comment</textarea>
  <a href="#" id="123_edit">Edit</a>
  <a href="#" id="123_save" class="hidden">Save</a>
</form>
</div>

采纳答案by cssyphus

You might find jQuery easier, and it's automatically cross-browser (and faster to type!) Since it's tagged on your question, here is the jQuery solution:

您可能会发现 jQuery 更容易,并且它会自动跨浏览器(并且输入速度更快!)由于它已标记在您的问题上,因此这是 jQuery 解决方案:

Edit: The tag jQuerywas removed from the original question on May 25 '19 at 21:10 (3 years after question was asked and answered), by user John, with the inexplicable editor comment "remove spam tags".

编辑:该标签jQuery已于 2019 年 5 月 25 日 21:10(在提出并回答问题后 3 年)由用户从原始问题中删除John,并带有莫名其妙的编辑评论“删除垃圾邮件标签”。

jsFiddle Demo

jsFiddle Demo

$('[id^=edit_]').click(function(){
    var id = this.id.split('_')[1];
    $('#'+id).addClass('hidden');
    $('#edit_'+id).addClass('hidden');

    $('#save_'+id).removeClass('hidden');  
    $('#editable_'+id).removeClass('hidden');  
});

$('[id^=save_]').click(function(){
    var id = this.id.split('_')[1];
    $('#'+id).removeClass('hidden');
    $('#edit_'+id).removeClass('hidden');

    $('#save_'+id).addClass('hidden');  
    $('#editable_'+id).addClass('hidden');  
});


Note that I switched around the id_number and the idName_ prefix. This makes it much easier to target those elements using the starts withselector: id^=

请注意,我切换了 id_number 和 idName_ 前缀。这使得使用starts with选择器定位这些元素变得更加容易:id^=

回答by blurfus

If using HTML4 ids must start with a letter (https://www.w3.org/TR/html4/types.html#type-id)

如果使用 HTML4id必须以字母开头 ( https://www.w3.org/TR/html4/types.html#type-id)

If using HTML5 you can use numbers.

如果使用 HTML5,您可以使用数字。

Either change your ids to start with a letter (as in id="p12345") or use HTML5 (i.e. use <!DOCTYPE html>at the top of your document)

ids更改为以字母开头(如id="p12345")或使用 HTML5(即<!DOCTYPE html>在文档顶部使用)

回答by Jovan Novakovic

You can use template string literals for this because id must be in quotes otherwise it won't work and be sure to use HTML5 at the top of your document. With this I didn't have any more issues.

您可以为此使用模板字符串文字,因为 id 必须用引号引起来,否则将无法使用,并确保在文档顶部使用 HTML5。有了这个,我没有更多的问题。

For example:

例如:

document.querySelector(`[data-id="${id}" ]`);

Or if for any reason you don't want to use template literals add this line of code:

或者,如果出于任何原因您不想使用模板文字,请添加以下代码行:

document.querySelector("[data-id=" + "\'" + id + "\'" + "]");

With escape character \'in double quotes.

\'在双引号中带有转义字符。

Hope this helps.

希望这可以帮助。

回答by Atif Hussain

document.querySelector("class or id")is not using tags as arguments instead it uses class or Id.

document.querySelector("class or id")不使用标签作为参数,而是使用类或 Id。