nearest()不适用于表

问题描述 投票:0回答:1

我有一个html页面,我正在实现“添加更多”功能。当用户单击add more链接时,会在表中创建新的<tr>。请参阅下面的代码:

<?php 
$city_more_attributes = array("empty" => "--- Select City ---","id" =>"morecitylist", "class" => "more_locations_list","onchange" => "load_sublocations(this.value)");
?>


var counter = 0;

$('#add_more_city').click(function(e){
    e.preventDefault();
    counter++;
    //var city = '<?php echo json_encode($city_more); ?>';
    var city = '<?php  echo json_encode($form->select("GalStore.gal_location_id_'+counter+'", $gal_locations,null,$city_more_attributes)); ?>';
    var more_cities_elements = '';
    more_cities_elements += '<tr id="morecities_show_'+counter+'" class="morecities">';             
    more_cities_elements += '<td>Add City</td>';
    more_cities_elements += '<td id="more_'+counter+'"></td>';
    more_cities_elements += '<td><a href="#" id="more_close_'+counter+'" onclick="close_box('+counter+')">X</a></td>';
    more_cities_elements += '</tr>';
    //alert(more_cities_elements);

    if(counter == 1){
        $('#addmoreanchor').after(more_cities_elements);
    }else if(counter > 1){
        var mcshwid = counter - 1;
        $('#morecities_show_'+mcshwid).after(more_cities_elements);
    }
    $('#more_'+counter).html(city);

    var noofcities = $('.morecities').size();
    $('#counter').val(noofcities);

});

上面的代码生成一个<tr>与独特的id。在<tr>内,线more_'+counter).html(city);产生和<select> list,其中添加了onchange = "load_sublocations(this.value)"事件。在这个函数中,我写道:

function load_sublocations(gal_location_id) {
var trid = $(this).closest('tr').attr('id');
alert(trid);
}

但不幸的是它警告undefined!什么原因 ?为什么它没有显示tr id

jquery html-table cakephp-1.3 closest
1个回答
3
投票

由于你使用的是内联事件处理程序,处理程序内部的this不引用被点击的元素,它引用了window元素,因此将clicked元素作为参数传递给handler方法,如下所示

load_sublocations(this)

然后

function load_sublocations(el) {
var gal_location_id = this.value;
var trid = $(el).closest('tr').attr('id');
alert(trid);
}
© www.soinside.com 2019 - 2024. All rights reserved.