使用jQuery使用多个.on()方法设置和获取对象

时间:2015-07-20 09:58:19

标签: javascript jquery get set

我有这个过程:

  1. 用户点击项目(Postee对象为SET)
  2. 用户点击帖子(Postee对象为GET并用于提交)
  3. 我的代码如下所示:

    <html>
    <head>
     <style>
    th, td { white-space: nowrap;}
     </style>
    </head>
     <body>
      <table>
    <tr>
    <th>testtest test</th>
    <th>zxcccccccxacasdwqeqw wqeewqeqe</th>
    <th>testtetwtwewadwad wdadwad wdadwad twetewtetw etwtewtw</th>  
    <th>testtetwtwetwetewtetw etwtewtw</th>
    <th>testtetwtwetwetewtetw etwtewtw</th>
    <th>testtetwtwetwetewtetw etwtewtw</th>
    <th>testtetwtwetwetewtetw etwtewtw</th>
    <th>testtetwtwetwetewtetw etwtewtw</th>
    <th>testtetwtwetwetewtetw etwtewtw</th>
    <th>testtetwtwetwetewtetw etwtewtw</th>
    </tr>
    <tr>
    <td>test test</td>
    <td>daw dawdawd awd awd awd awd</td>
    <td>d wadwaeqeeqw ewqeqwewq eqw</td>
    <td>d wadwaeqeeqw ewqeqwewq eqw</td>
    <td>d wadwaeqeeqw ewqeqwewq eqw</td>
    <td>d wadwaeqeeqw ewqeqwewq eqw</td>
    <td>d wadwaeqeeqw ewqeqwewq eqw</td>
    <td>d wadwaeqeeqw ewqeqwewq eqw</td>
    <td>d wadwaeqeeqw ewqeqwewq eqw</td>
    <td>d wadwaeqeeqw ewqeqwewq eqw</td>
    </tr>
    </table>
     </body>
    </html>
    

    有人知道我点击$(document).ready(function () { var postee; //SHARE FEED ITEM START $(document).on('click', '.feed-item-share', function(e){ var $this = $(this); var feed_item = $this.closest('.feed-item'); var postee = { object_id : feed_item.attr('data-feed-item-object-id'), type : feed_item.attr('data-feed-item-type'), user_id : feed_item.attr('data-feed-item-user-id'), id : feed_item.attr('data-feed-item-postee-id'), name : feed_item.attr('data-feed-item-postee-name'), img_id : feed_item.attr('data-feed-item-postee-img-id') } console.log("Postee: "+postee); }); $('#share_post_button').on('click', function (e) { console.log(postee); e.preventDefault(); console.log('Post Click'); }); }); 时无法获取postee对象的原因吗?控制台日志返回时出现未定义的变量错误。提前谢谢。

1 个答案:

答案 0 :(得分:2)

问题是因为您在postee点击处理程序中重新定义了.feed-item-share变量,因此它超出了#share_post_button点击处理程序的范围。删除var。另请注意,您应该使用data()来检索data-*属性,因为它是从jQuery的内部缓存中读取的,并保存了DOM读取。

试试这个:

postee = {
    object_id : feed_item.data('feed-item-object-id'),
    type : feed_item.data('feed-item-type'),
    user_id : feed_item.data('feed-item-user-id'),
    id : feed_item.data('feed-item-postee-id'),
    name : feed_item.data('feed-item-postee-name'),
    img_id : feed_item.data('feed-item-postee-img-id')
}