我正在尝试创建一种编辑一堆注释的方法,并通过我可以生成的一些id来识别它们。我遇到的错误是:
SyntaxError:无法在'Document'上执行'querySelector':'#1234'不是有效的选择器。但是,我不知道这是怎么可能的,因为我明显在id=1234
有<p>
。
此外,还有一些问题,当我评论其他所有内容并执行警报(id)时,这不适用于第二种形式,错误是:
TypeError:无法读取null的属性'classList'。
这是jsfiddle:qazxsw poi
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;
}
您可能会发现jQuery更容易,并且它会自动跨浏览器(并且输入速度更快!)因为它标记在您的问题上,所以这里是jQuery解决方案:
//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>
jsFiddle Demo
请注意,我切换了id_number和idName_前缀。这使得使用$('[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');
});
选择器:starts with
更容易定位这些元素
如果使用HTML4 id^=
s必须以字母开头(id
)
如果使用HTML5,您可以使用数字。
要么将https://www.w3.org/TR/html4/types.html#type-ids更改为以字母开头(如id
),要么使用HTML5(即在文档顶部使用id="p12345"
)
您可以使用模板字符串文字,因为id必须在引号中,否则它将不起作用并确保在文档顶部使用HTML5。有了这个,我没有任何问题:
例如
<!DOCTYPE html>
或者如果您不想以任何理由使用模板文字,请添加以下代码行:
document.querySelector(`[data-id="${id}" ]`);
希望这可以帮助。
document.querySelector("[data-id=" + "\'" + id + "\'" + "]"); with escape character \' in double quotes
不使用标签作为参数,而是使用类或Id。