将绑定函数包装到THIS元素

Jquery - wrapping a bind function to THIS elements

本文关键字:THIS 元素 包装 绑定 函数      更新时间:2023-09-26

我在一个页面上有多个表(将有超过100个),我想为所有这些使用一个函数。当用户在下拉菜单中选择"Custom"时,附加问题将适用于所有这些选项。我如何在THIS语句中包装我的函数,以使其仅添加到单个表中。我为我对这个问题的描述提前道歉。

$(document).ready(function(){
  $('td.additional_content').css('visibility', 'hidden');
  $('#srds_mapping').bind('change', function (e) { 
        if( $('#srds_mapping').val() == 'Custom') {
            $('td.additional_content').css('visibility', 'visible');
            $('td.additional_content .custom').show();
        } else {
            $('td.additional_content').css('visibility', 'hidden');
            $('td.additional_content .custom').hide();
        }
  }).trigger('change');
});

最好看一下

http://jsfiddle.net/2Q7J7/2/

this是事件处理程序中的目标元素:

$('#srds_mapping').bind('change', function (e) {
    if( $(this).val() == 'Custom') { // traverse to find the target input element

注意,您不应该在页面上使用多个ID。使用类或其他选择器代替,f.ex:

$('select').bind('change', function (e) {
    if( $(this).val() == 'Custom') {

jQuery .each()函数将是一个不错的选择:

假设$('#srds_mapping')是您的表。首先,您可以向表中添加一个类,而不是id。例如<table id="srds_mapping" class="srds_mapping"></table>。在此之后,您可以执行如下操作:

$('.srds_mapping').each(function(){
   $(this).bind('change', function (e) {
     // other function stuff
   }).trigger('change');
});

还有,这个帖子可能值得一读,或者值得思考。