【发布时间】:2016-01-13 21:34:59
【问题描述】:
我正在尝试创建一种方法来编辑一堆 cmets 并通过我可以生成的一些 id 来识别它们。我遇到的错误是:
语法错误:无法在“文档”上执行“querySelector”:“#1234”不是有效的选择器。但是,我看不出这是怎么可能的,因为我在<p> 中显然有id=1234。
此外,当我评论其他所有内容并执行警报(id)时,这对第二种形式不起作用,错误是:
TypeError:无法读取 null 的属性“classList”。
这是在 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>
【问题讨论】:
-
如果使用 HTML4
ids 必须以字母 (w3.org/TR/html4/types.html#type-id) 开头,而 HTML5 则可以使用数字。将您的ids 更改为以字母开头或使用 HTML5 -
你不能使用 JQuery 有什么原因吗?它使这样的 DOM 操作更容易(并且语法更简洁)
-
不明白你为什么不使用getElementById
标签: javascript html css