dongou1970 2013-09-06 23:48
浏览 57
已采纳

jQuery事件目标元素属性检索

I'm having some trouble pulling attributes from an event target element.

I am using php to access a mysql database. From the query I pull out some image file names and their respective id's. I then display these images in a table with the following line:

print '<td><img id="img_' . $row['paint_id'] . '" class="thumb_target" src="img/paint/thumb/' . $row['paint_thumb'] .'"></td>';

As you can see, this line gives each image the id 'img_xx' where xx is the images numeric id in the sql database. I also give each image the class 'thumb_target'. In document ready I set a .click event for the thumb_target elements. This makes an AJAX call which should pass the img_xx id as data. I got this to work in chrome using

data: 'imgID=' + event.target.id

However, several hours later I decided to check something else in firefox and found that it doesn't work for all browsers. Using jQuery's method:

var id = $(this).attr('id');

I can't get id to be anything but undefined. Am I targeting a different element than the element I think I am?

Here's the pertinent javascript:

function runClick() {
  var id = $(this).attr('id');
  alert(id);
  $.ajax({
    url: 'overlay.php',
    //~ data: 'imgID=' + event.target.id,
    //~ data: ({ imgID: id }),
    data: 'imgID=' + id,
    dataType: 'json',
    success: function(data, textStatus, jqXHR) {
        processJSON(data);
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert("Failed to perform AJAX call! textStatus: (" + textStatus +
              ") and errorThrown: (" + errorThrown + ")");
    }
  });
}

$(document).ready( function() {
  $('.thumb_target').click( function() {
    runClick();
  });

  $('#overlay').hide();
});

Here's a link to the test page: http://www.carlthomasedwards.com/painting2.php

  • 写回答

2条回答 默认 最新

  • dtvdz911959 2013-09-06 23:59
    关注

    runClick is executed in global scope, so this refers to the global object(window).

    Use that instead:

    $('.thumb_target').click( function(event) {
        runClick.apply(this);
      });
    

    or even more simple:

    $('.thumb_target').click( runClick);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大