最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - mvc dropdownlist - capturing change event without attaching the event handler - Stack Overflow

programmeradmin2浏览0评论

I know I can attach change event to html.dropdownlist in mvc as shown below:

$('#ddList').change(function() {
            var value = $(this).val();


        });

However, is there a way I can do it more like

 <%=Html.DropDownList("ddList", Model.dropDown, new { @class = "Ddl", change = "ddListChange"  })%>

js function below:

function ddListChange() {
        alert("test");
    }

Also, is one more approach more preferred than the other?

I know I can attach change event to html.dropdownlist in mvc as shown below:

$('#ddList').change(function() {
            var value = $(this).val();


        });

However, is there a way I can do it more like

 <%=Html.DropDownList("ddList", Model.dropDown, new { @class = "Ddl", change = "ddListChange"  })%>

js function below:

function ddListChange() {
        alert("test");
    }

Also, is one more approach more preferred than the other?

Share Improve this question asked Nov 12, 2010 at 0:59 TPRTPR 2,57710 gold badges41 silver badges66 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

Yes, you were close, as the onchange attribute was what you were looking for.

<%= Html.DropDownList("ddList", Model.dropDown, new { @class = "Ddl", onchange = "ddListChange" }) %>

jQuery skips the on part of the event names in its methods/parameters for events, e.g. .click(...) / .bind('click',..) equals the onClick attribute.

Binding event handlers using javascript itself is the preferred way. Just like you separate styling into separate CSS files, you separate scripting into your own scripting files. This allows the HTML file to be cleaner and easier to read, in addition to separating the concerns of prensentation and whatever your scripts is doing. It also makes it easier for you page to degrade gracefully (work even if scripts aren't enabled).

Here is one article discussing the issue

发布评论

评论列表(0)

  1. 暂无评论