【问题标题】:Data object in jquery is undefined after replaceWith替换后jquery中的数据对象未定义
【发布时间】:2012-03-19 07:29:02
【问题描述】:

我正在编写一个 jquery 插件,我需要一些按钮来获得双重状态(如编辑/保存) 我通过 JSON 获取此信息并将其插入按钮中:

node
    - current //['primary'/'secondary']
    - primary // some info
    - secondary // some info

单击按钮后,我会在此处更改操作。所以我想通过一个模板和我从 button.data 获得的信息来替换整个链接。 因为我不仅要替换innerHtml,还要替换外部,所以我必须使用'replaceWith'。然后我将“数据”复制到新按钮并(理想情况下)删除旧按钮。

changeButtonAction : function(button, selector){
      var node = button.data('node'),
           info;

      if(node.current == 'primary'){
           info = node.secondary;
           node.current = 'secondary';
      }else{
           info = node.primary;
           node.current = 'primary';
      }

      button.replaceWith(multiReplace(OPERATION_ITEM, info, true));
      button.data('node', $.extend( true, {}, node));

      ... //bit of interaction
 }

问题是:一旦退出函数我丢失了新数据,因为它说它是未定义。 有人可以帮忙吗?使用“replaceWith”不是必须的,所以如果你想出另一个解决方案就可以了。

【问题讨论】:

  • 如果可能,请在jsfiddle.net 进行演示,以便其他人更好地了解您的问题。无需复制所有代码,只需复制问题所在的部分即可。使用左侧的“添加资源”添加其他 js 文件。

标签: javascript jquery undefined replacewith


【解决方案1】:

好的,我解决了。

感谢 Diode,我尝试在 jsfiddle 中重现它。单击功能也不起作用,因此我稍微更改了代码。而不是用文本替换:

button.replaceWith(multiReplace(OPERATION_ITEM, info, true));
button.data('node', $.extend( true, {}, node));

用一个对象来做:

var button2 = $(multiReplace(OPERATION_ITEM, info, true))
    .data('node', $.extend( true, {}, node));
button.replaceWith(button2);

您可以看到它的实际效果: http://jsfiddle.net/p8vMR/9/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2014-09-14
    相关资源
    最近更新 更多