<strong class="comment" id="comment[6]">Show comments</strong>
<div id="comments[6]">HERE GO COMMENTS</div>
还有我的 JS 文件:
$(document).ready(
function() {
$(".comment").click(
function() {
var id = $(this).attr("id").replace("comment", "comments");
//document.getElementById(id).style.display = 'none';
$('#' + id).hide();
} );
});
HTML 代码是用 PHP 生成的,因此有很多带编号的 div,每次单击都会显示/隐藏相应的 div。但问题是,就 Javascript 而言(注释行)一切正常,但当我尝试使用 jQuery 时,什么也没有发生。问题出在哪里?
最佳答案
那是因为square brackets have special meaning within a jQuery selector .如果实际 id 包含方括号,则需要使用反斜杠将其转义:
var id = $(this).attr("id")
.replace("comment", "comments")
.replace(/(\[|])/g,"\\$1");
关于javascript - jQuery 隐藏/显示不起作用,不像 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18042357/