我正在尝试创建一种方法来编辑一堆评论并通过我可以生成的一些 ID 来识别它们。我遇到的错误是:
语法错误:无法在“文档”上执行“querySelector”:“#1234”不是有效的选择器。但是,我看不出这是怎么可能的,因为我在 id=1234
<p>
。
此外,还有一些问题,当我评论其他所有内容并执行 alert(id) 时,这对第二种形式不起作用,错误是:
类型错误:无法读取 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>
原文由 user4634820 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可能会发现 jQuery 更简单,并且它会自动跨浏览器(并且输入速度更快!)因为它已标记在您的问题上,所以这里是 jQuery 解决方案:
编辑:标签
jQuery
于 2019 年 5 月 25 日 21:10(问题被问及回答后 3 年),由用户John
从原始问题中删除,带有莫名其妙的编辑评论“删除垃圾邮件标签”。jsFiddle 演示
请注意,我调换了 idnumber 和 idName 前缀。这使得使用
starts with
选择器更容易定位这些元素:id^=