jQuery preventDefault()在我的MVC应用程序中不起作用

时间:2015-08-12 19:53:12

标签: jquery ajax asp.net-mvc

我正在尝试使用部分视图将我的javascript添加到项目列表中。在我的主页面中,我定义了列表和按钮以添加如下行:

<div class="col-md-9">
    @Html.Label("List Options", htmlAttributes: new { @class = "control-label" })
    @if (Model.CustomFieldOptions != null)
    {
        <div id="editorRows">
            @foreach (var cfItem in Model.CustomFieldOptions)
            {
                Html.RenderPartial("_CustomFieldOptionEditorRow", cfItem);
            }
        </div>
    }
    @Html.ActionLink("Add another...", "_AddOptionEditorRow", null, new { id = "addItem" })
</div>

我的javascript看起来像这样(更新):

$("#addItem").click(function (evt) {
    evt.preventDefault();
    $.ajax({
        url: this.href,
        cache: false,
        success: function(html) {
            $("#editorRows").append(html);
            return false;
        }
    });
    return false;
});

我的控制器操作定义如下:

public PartialViewResult _AddOptionEditorRow()
{
    return PartialView("_CustomFieldOptionEditorRow", new CustomFieldOption());
}

页面的这一部分呈现如下:

<div class="col-md-9">
    <label class="control-label" for="List_Options">List Options</label>
    <div id="editorRows">   
        <div class="editorRow">
            ...
        </div>   
        <div class="editorRow">
            ...
        </div>
    </div>
    <a href="/customforms/_addoptioneditorrow" id="addItem">Add another...</a>
</div>

当我点击按钮时,我会导航到:

  

http://localhost:63595/customforms/_addoptioneditorrow

我宁愿把它添加到div'editorRows'。

1 个答案:

答案 0 :(得分:2)

根据您this.href引用$.ajax({url...});来判断#addItem是否为锚标记。默认情况下,锚标记用于导航,因此要将其用于其他内容,您需要阻止默认操作:

$("#addItem").click(function(evt) {    // <-- Add the event parameter "evt"
    evt.preventDefault();    // <-- Add this line
    $.ajax({
        url: this.href,
        cache: false,
        success: function(html) { $("#editorRows").append(html); }
    });
    return false;
});