JQuery绑定this和data-attribute

时间:2016-01-18 06:54:41

标签: javascript jquery

我希望有一个点击侦听器,它可以绑定对象值本身以及已单击的元素的数据属性。

示例:

user.observe('after save', function function_name(ctx, next) {
  if (ctx.instance) {
    if(ctx.isNewInstance) {

      // look up role based on type
      //
      Role.find({where: {name: 'role-name'}}, function(err, role) {
        if (err) {return console.log(err);}

        RoleMapping.create({
          principalType: "USER",
          principalId: ctx.instance.id,
          roleId: role.id
        }, function(err, roleMapping) {

          if (err) {return console.log(err);}

          console.log('User assigned RoleID ' + role.id + ' (' + ctx.instance.type + ')');

        }):

      });

    }
  }
  next();
});

HTML:

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

我不知道如何在sayHello函数中获取数据属性。但我需要sayHello函数中的firstName和data-url。

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

我认为这是你正在寻找的(未经测试,但它会帮助你):

$(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);
};

答案 1 :(得分:0)

更新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");

答案 2 :(得分:0)

使用getAttribute javascript函数,尝试

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