JQuery 绑定此和数据属性

JQuery bind this and data-attribute

本文关键字:数据属性 绑定 JQuery      更新时间:2023-09-26

我想要一个点击侦听器,它绑定对象值本身和被点击的元素的数据属性。

例:

var Person = function (firstName) {
  this.firstName = firstName;
  $(window).on("click", ".myclass", sayHello).bind(this);
};
Person.prototype.sayHello = function() {
  console.log("Hello, I'm " + this.firstName + data-url);
};
var person1 = new Person("Alice");

.HTML:

<div class="wrapper">
  <a href="#" data-url="google.com" class="myClass">Test</a>
  <a href="#" data-url="google.com" class="myClass">Test</a>
  <a href="#" data-url="google.com" class="myClass">Test</a>
</div>

我不知道如何在sayHello函数中获取数据属性。但是我需要sayHello函数中的名字和数据网址。

有什么建议吗?

我认为这就是您正在寻找的(未经过测试,但它会对您有所帮助):

$(a).click(function(){
   data_val = $(this).data('url');//will give you data attribute value of clicked anchor element
   var person1 = new Person("Alice", data_val);
}); 
var Person = function (firstName, val) {
  this.firstName = firstName;
  this.val = val;
};
Person.prototype.sayHello = function() {
  console.log("Hello, I'm " + this.firstName + this.val);
};

更新 sayHello 方法以接受其他参数并创建指向 Person 对象this的链接:

var Person = function (firstName) {
  var self = this;
  this.firstName = firstName;
  $(window).on("click", ".myclass", function() {
    self.sayHello(this);
  });
};
Person.prototype.sayHello = function(element) {
  console.log("Hello, I'm " + this.firstName + $(element).data('url'));
};
var person1 = new Person("Alice");

使用getAttribute javascript函数,尝试

console.log("Hello, I'm " + this.firstName + this.getAttribute('data-url'));