繁体   English   中英

如何更改文本 <p> 用Jscript?

[英]How to change text of <p> using Jscript ?

我正在开发MVC应用程序并使用剃刀语法。

在这个应用程序中,我给予评论设施。

我用

显示评论

段。

<p id="ClassPara" class="ShowComments" onclick="chkToggle()">Show Comments</p>

现在,当用户点击“显示评论”时,我切换Div ,在该div中我显示评论。

现在,我想从“显示评论”中更改“隐藏评论”的文本,当用户点击该段时。

但是我无法将文本更改为“隐藏评论”...它会继续显示“显示评论”如何做到这一点?

我的代码是......

<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".ShowComments").click(function () {
            $(".ParentBlock").slideToggle("slow");
            if ($('.ShowComments').text = "Show Comments"
            {
               $('.ShowComments').text('Hide');
            }
            else
            {
               $('.ShowComments').text('Show Comments');
            }
        });
    });
</script>

.text不是一个属性的方法

.text(“显示评论”)或.text(“隐藏评论”)

比较它的.text()===“显示评论”

更新了您的代码并修复了一些错误。

<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".ShowComments").click(function () {
            $(".ParentBlock").slideToggle("slow");
            if ($('.ShowComments').text() === "Show Comments")
            {
               $('.ShowComments').text('Hide');
            }
            else
            {
               $('.ShowComments').text('Show Comments');
            }
        });
    });
</script>

您还在if条件中使用赋值运算符而不是比较运算符。 ==或===不=

您可以使用回调函数到.text()方法,如下所示,并简化您的代码。

$(document).ready(function() {
    $(".ShowComments").click(function() {

        $(".ParentBlock").slideToggle("slow");

        // here instead of .ShowComments you should use
        // this, where this refers to clicked element

        $(this).text(function(i, oldText) {
            return oldText == 'Show Comments' ? 'Hide' : 'Show Comments';
        });
    });
});​

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM