1

我能够成功显示/隐藏 div onclick。但是 onclick div 显示一秒钟,页面刷新。我用过javascript。代码:

       @{var Count = 0;}
 foreach (var commentlist in Model.Comments.Where(x => x.CommentParentID == 0))
  {
 <div id="@Count" style="display: none;">
<input type="submit" id="reply" class="reply-link" onclick="return showHide(@Count);" value="Reply" />
 @{Count++; }
</div>
}


<script type="text/javascript">
 function showHide(Count) {
        var ele = document.getElementById(Count);
        if (ele.style.display == "block") {
            ele.style.display = "none";           
        }
        else {
            ele.style.display = "block";
        }
    }
</script>
4

2 回答 2

0

发生这种情况是因为您的页面正在提交。尝试使用<input type="button"...>而不是<input type="submit"...>

这里的区别: <input type='button' /> 和 <input type='submit' /> 之间的区别

并且您的控件 ID 不能以数字开头,并且必须是唯一的:

@{var Count = 0;}
foreach (var commentlist in Model.Comments.Where(x => x.CommentParentID == 0))
{
    <div id="div_@Count" style="display: none;">
        <input type="submit" id="reply_@Count" class="reply-link" onclick="return showHide('mydiv_@Count');" value="Reply" />
        @{Count++; }
    </div>
}
于 2013-01-07T07:26:14.747 回答
0

如果提交按钮在<form>您需要的内部return falseshowHide如果您不希望页面在单击后被提交:

<script type="text/javascript">
function showHide(Count) {
    var ele = document.getElementById(Count);
    if (ele.style.display == "block") {
        ele.style.display = "none";           
    }
    else {
        ele.style.display = "block";
    }

    return false; // <-- that's important to prevent the page from submitting
}
</script>

另外请记住,id属性不能以 HTML 中的数字开头。所以请修复你的标记:

@{var Count = 0;}
foreach (var commentlist in Model.Comments.Where(x => x.CommentParentID == 0))
{
    <div id="mydiv_@Count" style="display: none;">
        <input type="submit" id="reply" class="reply-link" onclick="return showHide('mydiv_@Count');" value="Reply" />
        @{Count++; }
    </div>
}


<script type="text/javascript">
function showHide(id) {
    var ele = document.getElementById(id);
    if (ele.style.display == "block") {
        ele.style.display = "none";           
    }
    else {
        ele.style.display = "block";
    }
    return false;
}
</script>
于 2013-01-07T07:26:54.717 回答