繁体   English   中英

jQuery将此绑定到数据属性

[英]JQuery bind this and data-attribute

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

例:

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函数中的firstName和data-url。

有什么建议么?

我认为这是您要寻找的(未经测试,但会有所帮助):

$(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方法接受额外PARAMS和创建一个链接到this Person对象的:

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'));

暂无
暂无

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

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