質問

I have a html page where I am implementing a "add more" feature. When a user clicks add more link, a new <tr> is created within the table. See tha code below :

<?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);

});

The above code produces a <tr> with an unique id. Within the <tr>, the line more_'+counter).html(city); produces and <select> list where onchange = "load_sublocations(this.value)" event is added . Within this function , I wrote :

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

But unfortunately it alerts undefined ! Whats the reason ? Why it is not showing the tr id ?

役に立ちましたか?

解決

since you are using inline event handler, this inside the handler does not refer to the clicked element, it refers the window element so pass the clicked element as an parameter to the handler method as shown below

load_sublocations(this)

then

function load_sublocations(el) {
var gal_location_id = this.value;
var trid = $(el).closest('tr').attr('id');
alert(trid);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top