[译]Pro ASP.NET MVC 3 Framework 3rd Edition (Chapter 20 JQuery) 5.Using jQuery Events 使用jQuery事件

The jQuery library includes a nice event handling system that supports all the underlying JavaScript events but makes them easier to use, consistent across browsers, and compatible with selectors. Listing 20-17 contains a demonstration.

jQuery库包含了一个很好的事件处理系统,它对所有的基础JavaScript事件提供了支持,而且使它们更加易用,在跨浏览器时保持一致,并兼容其选择器。清单20-17包含了一个示例:

Listing 20-17. Using jQuery Events

清单20-17.使用jQuery事件

 

<script type="text/javascript">

$(document).ready(function () {

$('table').addClass('summitTable');

$('tr:even').css('background-color', 'silver');

$(':submit[value="Reset"], a:contains("Add")')

.css('float', 'left')

.css('margin', '5px');

$('th:nth-child(2)').text('Height (m)').after('<th>Height (ft)</th>');

$('td:nth-child(2)')

.after('<td/>')

.each(function () {

$(this).next().text((parseInt($(this).text()) * 3.28).toFixed(0));

});

$('form[action$="/DeleteSummit"]').submit(function () {

var summitName = $(':hidden', this).attr('value');

return confirm('Are you sure you want to delete ' + summitName + ' ?');

});

});

</script>

    In this example, we have used the submit method to register a function that will be called when a form is submitted. We have selected those forms whose action attribute value ends with /DeleteSummit,which is the set of forms embedded within the HTML table and which are responsible for deleting individual summits from the list.

    在这个例子中,我们使用了提交方法去注册一个函数,这个函数会在一个表单提交时被调用。我们选择了那些action属性值以“/DeleteSummit”结尾的表单,这组表单嵌在HTML表格中,负责删除列表中的单个summits。

 

  The result that we return from the function determines whether the form will be submitted. If we return true, it will; if we return false, it won¡¯t. In this example, we generate a result by using the confirm function, which prompts the user, as shown in Figure 20-9.

  我们从函数返回的结果决定是否提交表单,如果我们返回true,它会提交;如果返回false,则不会提交。在这个例子中,我们使用一个确认函数生成一个结果来提醒用户,如图20-9所示:

image

Figure 20-9. Prompting the user before deleting a summit from the list

图20-9.在删除列表中的一个summit之前提醒用户

 

  In this way, we have added a prompt that requires the user to confirm that they want a summit to be deleted before the form is submitted. Notice how easy it was to add the event handler to all the selected form elements. We just use a regular jQuery selector and called the submit method to register our function. jQuery takes care of everything else. jQuery supports all the underlying JavaScript events; for full details, consult the jQuery API reference.

  通过这种方式,我们添加一个提示要求用户在表单提交前去确认他们想删除一个summit。注意,将事件处理添加到所有被我们选中的表单元素中是的多么简单,我们仅仅需要使用一个常规的jQuery选择器,然后调用提交方法注册我们的函数,jQuery会自行处理剩下的一切。jQuery支持所有的基础JavaScript事件,详细信息请查阅jQuery API参考。

你可能感兴趣的:(framework)