Javascript dom操纵数据对象

时间:2020-12-03 16:25:50

I have HTML like this

我有像这样的HTML

<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>

I want to convert it become like this

我想转换它变得像这样

<div class="fruits">
<p id="pid_0" data-show="wid_0">
    <span id="wid_0" data-price="100" data-code="1">Banana</span>
    <span id="wid_1" data-price="200" data-code="2">Apple</span>
    <span id="wid_2" data-price="300" data-code="3">Orange</span>
    <span id="wid_3" data-price="400" data-code="4">Melon</span>
    <span id="wid_4" data-price="500" data-code="5">Papaya</span>
</p>
<p id="pid_5" data-show="wid_5">
    <span id="wid_5" data-price="600" data-code="6">Avocado</span>
    <span id="wid_6" data-price="700" data-code="7">Coconut</span>
    <span id="wid_7" data-price="800" data-code="8">Strawberry</span>
</p>

This is how I got so far

这就是我到目前为止的方式

<script>
var price_arr = [100, 200, 300, 400, 500, 600, 700, 800];
var code_arr = [1, 2, 3, 4, 5, 6, 7, 8];

$(".fruits").each(function() { 
    $(this).text($(this).text().replace(/\w+/g, "<span>$&</span>")); 
    $(this).text($(this).text().replace(/\[/g, "<p> ")); 
    $(this).text($(this).text().replace(/\]/g, "</p>")); 
});

var str = $(".fruits").text();
var words = str.split(" ");
var result = [];
var obj = {};

for (var i = 0; i < words.length - 1; i++) {
    // words
    words[i] += " ";

    var w = "wid_"+i;
    var p = "pid_"+i;

    var price = price_arr[i];
    var code = code_arr[i];
    var name = words[i] += " ";

    obj = {get_price:price, get_code:code, display:name};
    result.push(obj);
}
</script>

I'm want to use data object(obj) and store it to each html attribute, but I'm getting stuck. Anyone please help me, I will be highly appreciate.

我想使用数据对象(obj)并将其存储到每个html属性中,但我遇到了困难。有人请帮助我,我将非常感谢。

2 个解决方案

#1


1  

Simply use with Array#map function append() function of jquery

只需使用jquery的Array#map函数append()函数即可

  1. first separate the html data in to two array
  2. 首先将html数据分成两个数组

  3. Then map with each array.
  4. 然后映射每个数组。

  5. Finally map with each array with in arguments.
  6. 最后用in参数映射每个数组。

  7. Then append with in a fruits
  8. 然后加入水果

var price_arr = [100, 200, 300, 400, 500, 600, 700, 800];
var code_arr = [1, 2, 3, 4, 5, 6, 7, 8];

var a = $('.fruits').text().split('][')
$('.fruits').empty()
var k = 0;
var c = 0;
var result = []
var res = [];
a.map((a, b) => {
  $('.fruits').append('<p id="pid_' + k + '" data-show="wid_' + k + '"></p>')
  a.replace(/\]|\[/g, "").split(" ").map((a, b) => {
    if (a) {
      result[c] = {
        get_price: price_arr[c],
        get_code: code_arr[c],
        display: a,
      };
      $('#pid_' + k + '').append('<span id="wid_' + c + '" data-price="' + price_arr[c] + '" data-code="' + code_arr[c] + '">' + a + '</span>')
      c++;
    }
  })
  k = c
})
console.log(result);
console.log($('.fruits').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>

#2


1  

You can parse the .textContent of .fruits element to create an array using .replace(), JSON.parse(); use $.map() to create html from array elements, set .innerHTML of .fruits using .html().

您可以使用.replace(),JSON.parse();解析.fruits元素的.textContent来创建数组。使用$ .map()从数组元素创建html,使用.html()设置.fruits的.innerHTML。

Increment variables storing 0, 0, 1, 0 for id of p elements, id of span elements, "code" and "price" data-* attributes set with data at jQuery(html, attributes)

增量变量存储0,0,1,0表示p元素的id,span元素的id,“code”和“price”data- *用jQuery(html,attributes)数据设置的属性

var fruit = $(".fruits");
var data = fruit.text()
           .replace(/(\w+)/g, "\"$1\",")
           .replace(/,(?=\s])/g, "")
           .replace(/\]\[/, "],[");
var id = 0;
var s = 0;
var w = 1;
var n = 0;

var html = $.map(JSON.parse("[" + data + "]"), function(el) {
  var p = $("<p>", {
            id: "pid_" + id,
            html: $.map(el, function(_fruit) {
                    return $("<span>", {
                             id:"wid_"+ (s++),
                             text: _fruit + "\n"
                           })
                           .attr({
                             "data-price": (n += 100),
                             "data-code": w++
                           })
          })
  }).attr("data-show", "wid_" + id);

  id += 5;
  return p;
});

fruit.html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>

#1


1  

Simply use with Array#map function append() function of jquery

只需使用jquery的Array#map函数append()函数即可

  1. first separate the html data in to two array
  2. 首先将html数据分成两个数组

  3. Then map with each array.
  4. 然后映射每个数组。

  5. Finally map with each array with in arguments.
  6. 最后用in参数映射每个数组。

  7. Then append with in a fruits
  8. 然后加入水果

var price_arr = [100, 200, 300, 400, 500, 600, 700, 800];
var code_arr = [1, 2, 3, 4, 5, 6, 7, 8];

var a = $('.fruits').text().split('][')
$('.fruits').empty()
var k = 0;
var c = 0;
var result = []
var res = [];
a.map((a, b) => {
  $('.fruits').append('<p id="pid_' + k + '" data-show="wid_' + k + '"></p>')
  a.replace(/\]|\[/g, "").split(" ").map((a, b) => {
    if (a) {
      result[c] = {
        get_price: price_arr[c],
        get_code: code_arr[c],
        display: a,
      };
      $('#pid_' + k + '').append('<span id="wid_' + c + '" data-price="' + price_arr[c] + '" data-code="' + code_arr[c] + '">' + a + '</span>')
      c++;
    }
  })
  k = c
})
console.log(result);
console.log($('.fruits').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>

#2


1  

You can parse the .textContent of .fruits element to create an array using .replace(), JSON.parse(); use $.map() to create html from array elements, set .innerHTML of .fruits using .html().

您可以使用.replace(),JSON.parse();解析.fruits元素的.textContent来创建数组。使用$ .map()从数组元素创建html,使用.html()设置.fruits的.innerHTML。

Increment variables storing 0, 0, 1, 0 for id of p elements, id of span elements, "code" and "price" data-* attributes set with data at jQuery(html, attributes)

增量变量存储0,0,1,0表示p元素的id,span元素的id,“code”和“price”data- *用jQuery(html,attributes)数据设置的属性

var fruit = $(".fruits");
var data = fruit.text()
           .replace(/(\w+)/g, "\"$1\",")
           .replace(/,(?=\s])/g, "")
           .replace(/\]\[/, "],[");
var id = 0;
var s = 0;
var w = 1;
var n = 0;

var html = $.map(JSON.parse("[" + data + "]"), function(el) {
  var p = $("<p>", {
            id: "pid_" + id,
            html: $.map(el, function(_fruit) {
                    return $("<span>", {
                             id:"wid_"+ (s++),
                             text: _fruit + "\n"
                           })
                           .attr({
                             "data-price": (n += 100),
                             "data-code": w++
                           })
          })
  }).attr("data-show", "wid_" + id);

  id += 5;
  return p;
});

fruit.html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fruits">[ Banana Apple Orange Melon Papaya ][ Avocado Coconut Strawberry ]</div>