繁体   English   中英

获取动态创建的绑定链接的href

[英]Get href of dynamically created bound link

我有一些在表中动态创建的链接,这些链接的href发送一个GET请求删除用户。 我有这样的听者绑定:

var $usersTableBody = $('#table-users tbody');
var $deleteUserBtn = $('.delete-user-btn');
$usersTableBody.on('click', $deleteUserBtn, deleteConfirm);

我需要得到href$deleteUserBtn ,问题是,现在我不能得到的链接<a> ,我点击,因为该事件被绑定到表身。 那么...我该怎么做呢?

为您轻松

//                                  this argument should be a string
//                                  ↓
$('#table-users tbody').on('click', '.delete-user-btn', function(e) {
    alert(this.href); // "this" is the event target / source
});

参见http://api.jquery.com/on/#on-events-selector-data-handler

选择器
类型: 字符串
一个选择器字符串,用于过滤触发事件的所选元素的后代。

$(document).on("click", "a.delete-user-btn", function(event) {
  // prevent default action, to not affect any other 
  // event handlers attached to `a.delete-user-btn`
  event.preventDefault();
  // do stuff with `this` : `a.delete-user-btn` `href` property
  console.log(this.href)
})

首先,请参阅jQuery的文档 ,因为您没有使用正确的参数。

我不知道您的HTML的确切性质,但是您可以使用事件回调对象的target属性来确定href:

$usersTableBody.on('click', function(e) {
    var $target = jQuery(e.target);
    alert('clicked: ' + $target.attr('href'));
    deleteConfirm();

    // delete action
});

参见此jsbin的另一个示例: https ://jsbin.com/huzegufihe/edit?html,输出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM