当 html 被回显时调用 html attr


Calling an html attr when html is echo'd

我正在通过将 html 从我的控制器回显到 ajax 函数来创建列表。 所以我的JavaScript通过Ajax获取这些数据并创建li的... 然后我想从这个创建的 html 中调用一个属性......它不起作用。...我做错了什么?

爪哇脚本

创建列表

$.ajax({
             url:'ol_locations',  // ol_locations is a controller, see below.
             dataType: 'html',
                success: function (data3){
            //  list elements in the ordered list

            $('ol.locations_list').html(data3);
                }});
//list populated successfully

控制器ol_location

公共函数 ol_locations(){

    $this->load->model('model_location');
    $data = $this ->model_location -> fetch_location_data();
    $i=1;
    foreach ($data as $row){

        if ($row->Type == 'locality'){
            echo "<div data-color ='red' id='".$i."'><li><a href ='#'> <span class='location_title'>". $row -> Nickname . " </span> ". $row->FormattedAddress .
            "</a> <a class='remove_location' title='Remove this location' data-nid='{$row->Id}'
            style='float:right;'>x</a>" ." </li> </div>";
            $i++;
        }
        else {
                 echo "<div data-color ='red' id='".$i."'><li> <a href ='#'><span class='location_title'>". $row -> Nickname. " ". $row -> Radius ." km of </span> ". " </span> ". $row->FormattedAddress ."</a><a class='remove_location' title='Remove this location' data-nid='{$row->Id}'style='float:right;'>x</a>" ." </li> </div>";
            $i++;
        } }
}

现在 HTML 呈现良好...但是当我尝试访问这个"创建的 html"中的任何元素时,没有任何反应......

例如警报($('#1')。 attr('color')); 将给出"null"或未定义。

我尝试了很多事情,例如

var initial_location = $('ol.locations_list li a'). attr('href');

仍然为空...

我真的被困在这里了...

由于您说 html 已正确添加到您的 DOM 中,因此您可能正在尝试在实际加载新元素之前访问它们。确保仅在$('ol.locations_list').html(data3);之后放置与新元素相关的任何代码,例如 -

$.ajax({
         url:'ol_locations',  // ol_locations is a controller, see below.
         dataType: 'html',
            success: function (data3){
        //  list elements in the ordered list

        $('ol.locations_list').html(data3);
}}).done(function() {
    alert ($("#1").attr('data-color'));
});