我有一个包含元素的数组,如下代码所示<div class="home_team" data-home='["10","20","30"]'></div>
当我从下面的输入中输入值时,我希望将该值插入到上面的数组中<input type="text" /><button class="update_home_timeline">update</button>
\
我设法插入了值(假设我输入了100(,但在某些情况下,它删除了数组中每个数据周围的方括号和分号,变成了下面的代码<div class="home_team" data-home="10,20,30100"></div>
JS
$('.update_home_timeline').on('click', function () {
newInput = $(this).prev().val();
$('.home_team').attr('data-home', dataHome + newInput);
});
如何避免像下面的代码示例那样删除方括号和分号<div class="home_team" data-home='["10","20","30","100"]'></div>
var arr = [];
var total = [];
$('.update_home_timeline').on('click', function() {
arr = [];
newInput = $(this).prev().val();
var str = $('.home_team').attr('data-home')
var res = str.split(",");
arr.push(newInput);
var total = res.concat(arr);
var x = total.toString();
$('.home_team').attr('data-home', x);
console.log('updated-data-in-element-data-home', $('.home_team').attr('data-home'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="home_team" data-home="10,20,30,100"></div>
<input type="text" /><button class="update_home_timeline">update</button>
你可以这样做。为你演奏小提琴:https://jsfiddle.net/bogatyr77/h9rktxuz/21/