php - jQuery 事件目标元素属性检索

标签 php javascript jquery this target

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

我正在使用 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

最佳答案

runClick 在全局范围内执行,因此 this 引用全局对象(window)。

使用它来代替:

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

或者更简单:

$('.thumb_target').click( runClick);

关于php - jQuery 事件目标元素属性检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18668197/

相关文章:

javascript - 用于 Rocket Chat iframe 身份验证的 NodeJS 应用程序抛出 SyntaxError : Unexpected token (

jquery - 使用 jquery show/hide 不会将 css 保留在 div 中

javascript - 使用 jQuery 构建元素时出现错误

javascript - 如何模拟输入元素上的输入事件?

jquery - 在我附加 jquery 代码以创建可扩展菜单后,我的 <a> 链接无法响应

PHP PDO异常 : "SQLSTATE[HY093]: Invalid parameter number"

javascript - 我怎样才能使图像出现在 html 网站正文中的 facebook 链接中?

php - 在 PHP 中按类(instanceof)切换

php - 如何使用 Doctrine 在死锁后重试事务?

Javascript 相当于 $.on