代码之家  ›  专栏  ›  技术社区  ›  sage88

jQuery事件目标元素属性检索

  •  0
  • sage88  · 技术社区  · 12 年前

    我在从事件目标元素中提取属性时遇到了一些问题。

    我正在使用php访问一个mysql数据库。从查询中,我提取了一些图像文件名和它们各自的id。然后,我将这些图像显示在带有以下行的表格中:

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

    正如您所看到的,这一行为每个图像提供id“img_xx”,其中xx是sql数据库中的图像数字id。我还为每个图像指定了类“thumb_target”。在“文档就绪”中,我为thumb_target元素设置了一个.click事件。这会产生一个AJAX调用,该调用应该将img_xx id作为数据传递。我用这个在chrome中工作

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

    然而,几个小时后,我决定在firefox中检查其他内容,发现它并不适用于所有浏览器。使用jQuery的方法:

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

    我不能让id成为任何东西,除非是未定义的。 我的目标元素与我认为的元素不同吗?

    以下是相关的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();
    });
    

    以下是测试页面的链接: http://www.carlthomasedwards.com/painting2.php

    2 回复  |  直到 12 年前
        1
  •  2
  •   Dr.Molle    12 年前

    runClick 在全局范围内执行,因此 this 指全局对象( window ).

    请改用该选项:

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

    或者甚至更简单:

    $('.thumb_target').click( runClick);
    
        2
  •  2
  •   Rafi    12 年前

    当浏览器执行时 runClick 这个 this 上下文未被保留。如果您在 Chrome debugger ,你可以看到 实际上 Window 什么时候 运行单击 被调用。

    绕过这个问题的方法是将元素传递到 运行单击 :

    function runClick(elem) {
      alert($(elem).attr('id'));
      ...
    }
    

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