X-editable 不能二次初始化的问题解决方案

最近用到了 X-editable 可编辑表格插件,发现了一个头疼的问题,X-editable 不能对同一个 <a> 元素二次初始化。

如下代码举例:在页面加载完成时,用“数组1”填充一个下拉框;然后单击按钮,用“数组2”再次填充该下拉框;此时点开下拉框,发现竟然还是“数组1”的数据。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="UTF-8">
 5     <link rel="stylesheet" href="plugins/bootstrap-3.3.7-dist/css/bootstrap.css" />
 6     <link rel="stylesheet" href="plugins/bootstrap3-editable/css/bootstrap-editable.css" />
 7     <title>可编辑表格试验</title>
 8     <script src="plugins/jquery-3.4.1.js"></script>
 9     <script src="plugins/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
10     <script src="plugins/bootstrap3-editable/js/bootstrap-editable.js"></script>
11 </head>
12 <body>
13     <h1>X-editable</h1>
14     <div id="div1">
15         <a href="#" id="target"></a>
16     </div>
17     <button onclick="fun()">click</button>
18 </body>
19 <script>
20 // 页面加载完后第一次初始化下拉框
21 $(function() {
22     var items = [{value: "giant", text: "捷安特"}, {value: "merida", text: "美利达"}];
23     $("#target").editable({
24         type: 'select',
25         mode: 'popup',
26         source: items,
27         sourceCache: false,
28         emptytext: '空值',
29         placement: 'bottom',
30         success: function(response, newValue) {
31             console.log(newValue);
32         }
33     });
34 });
35 // 单击按钮进行第二次初始化
36 function fun() {
37     // $("#div1").html("");
38     // $("#div1").html('<a href="#" id="target"></a>');
39     // $(function() {
40         var items2 = [{value: "geely", text: "吉利"}, {value: "gwm", text: "长城"}];
41         $("#target").editable({
42             type: 'select',
43             mode: 'inline',
44             source: items2,
45             sourceCache: false,
46             emptytext: '请选择',
47             success: function(response, newValue) {
48                 console.log(newValue);
49             }
50         });
51     // });
52 }
53 </script>
54 </html>
View Code

 

我的解决方案是把上面注释部分放开。也就是先将 <a> 目标从 DOM 中删除,然后用 jQuery 在原位置添加一个新的 <a> 元素,待元素创建好之后,再进行第二次初始化就可以了。

如果页面使用 Vue,那么道理也是一样。先将 Vue 绑定的页面数据存在一个临时变量中,然后清空 Vue 绑定的数据,待页面渲染完成之后,再将临时变量中的数据回填进 Vue 或进行其它进一步的操作。代码类似下面这样:

 1 var app = new Vue({
 2     el: '#app',
 3     data: {
 4         list: []
 5     },
 6     methods: {
 7         renderHtml: function(data) {
 8             var temp = app.list;    // 数据暂存入临时变量
 9             app.list = [];            // 清空绑定数据
10             $(function() {
11                 // 页面渲染完后再回填数据或进行其它进一步的操作
12                 app.list = data;
13                 // 进一步的操作……
14             });
15         }
16     }
17 });
View Code

 

对于这个问题,研究了一下 X-editable 源码,可惜水平有限,没看出来问题出在哪,于是暂时采用这种比较笨的办法。

posted @ 2019-05-05 19:21  印第安男人  阅读(292)  评论(0编辑  收藏  举报