我有一个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
?
答案 0 :(得分: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);
}