jQuery - 从传递给事件的另一个对象内访问对象属性 [英] jQuery - Accessing object properties from within another object that was passed to an event

查看:201
本文介绍了jQuery - 从传递给事件的另一个对象内访问对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在之前的问题我制定了如何将对象存储为属性
现在,当对象被传递一个事件但是不能访问那些属性让它工作:

In an earlier question I worked out how to store an object as properties. Now I am trying to access those properties when the object is passed through an event but can't get it to work:

<script language="javascript">
$(document).ready(function() {
    //create a TestObject
    function TestObject() {
      this.testProperty = "green";
    }

    //and an instance of it
    var testObject = new TestObject();

    //attach this instance to the div as a property
    var test;
    test = $('#test');//the div
    jQuery.data(test, "obj", testObject);

    //prove it worked and the TestObject is assigned
    alert(jQuery.data(test, "obj").testProperty);//works

    $('#test').click(TestClick);
    //test.click(TestClick); doesn't work either

    function TestClick() {
        alert($(this).attr("id"));//displays "test" - works
        alert(jQuery.data($(this), "obj").testProperty);
        //testProperty is null or not an object??
        //clearly TestObject is no longer attached to the div, why?
        //Or have I attached it the wrong way?    
        //alert(jQuery.data(this, "obj").testProperty); doesn't work either
    };
});
</script>
<body>
    <form id="form1" runat="server">
        <div id="test">Here is a test div</div>
    </form>
</body>


推荐答案

这将为您工作,将其附加到元素,而不是作为元素的引用,它似乎稍微改变(这是一个不同的 .data()调用,请参阅这里了解信息):

This will work for you, attach it to the element, not as a reference to the element which seems to change slightly (this is a different .data() call, see here for info):

$(document).ready(function() {
  function TestObject() {
    this.testProperty = "green";
  }

  var testObject = new TestObject();
  var test = $('#test').data("obj", testObject);

  alert(test.data("obj").testProperty);

  $('#test').click(TestClick);
  function TestClick() {
    alert($(this).attr("id"));
    alert($(this).data("obj").testProperty);
  };
});

这篇关于jQuery - 从传递给事件的另一个对象内访问对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆