【问题标题】:How do I clear a text EditorFor如何清除文本 EditorFor
【发布时间】:2014-11-11 00:02:08
【问题描述】:

我在 Razor 页面上有一个元素,如下所示:

<td>
    <div class="col-md-12">
        @Html.EditorFor(model => model.FreeTextName, new { htmlAttributes = new { @class = "form-control" } })
    </div>
</td>

当页面首次呈现时,其中包含提示文本,例如“输入名称以在此处搜索”

我希望当用户单击该字段时该文本消失,因此我编写了一个像这样的小脚本:

<script type="text/javascript">
    $('#FreeTextSwitchId').focusin(
        $('#FreeTextName').val("")
        )
</script>

但是现在我的页面在提示测试消失的情况下呈现。我知道是脚本在做这件事,因为如果我做这样的事情:$('#FreeTextName').val("test") 然后会出现“测试”而不是提示文本。

我在这里做错了什么?

【问题讨论】:

    标签: javascript jquery razor


    【解决方案1】:

    像这样使用你的@Html.EditorFor()

    @Html.EditorFor(model => model.FreeTextName, new { @class = "form-control" })
    

    现在你已经在@Html.EditorFor() 中给出了一个类,即.form-control。在你的脚本中使用你的类。像这样执行脚本:

    <script type="text/javascript">
    
        $('.form-control').on('blur click', function(){ 
            $(this).val("");
        });
    
    </script>
    

    此外,您还可以在 @Html.EditorFor() 中使用 placeholder="Your Hint" 属性,即:

    @Html.EditorFor(model => model.FreeTextName, new { @class = "form-control", placeholder="Enter name to search for here" })
    

    它是一个 html 输入 type="textbox" 属性,它自动将默认文本添加到文本框作为默认提示,以便用户可以理解该文本框中应该给出的内容。为此,您不需要使用任何脚本。

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      您是否要添加水印???您可以在 HTML5 中使用“占位符”属性

       &lt;input placeholder="example text" type="text" /&gt;

      【讨论】:

        【解决方案3】:

        您应该在输入中添加一个占位符。这是一个例子:http://jsfiddle.net/naeqgnd3/

        &lt;input placeholder="'Enter name to search for here" /&gt;

        当用户输入时文本会消失。

        【讨论】:

          【解决方案4】:

          我实际上决定使用MVC4 input field placeholder 中的最佳答案,因为我使用的是 MVC4:

          【讨论】:

            猜你喜欢
            • 2012-10-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-03-14
            相关资源
            最近更新 更多