如何从具有追加

时间:2019-06-10 10:19:04

标签: javascript jquery html object parameters

我有简单的“数据”,包括li标签和数据。 然后将其附加到“ ul”标签。 我希望每个li标签都可以单击以将其一些数据传递到txtBox。

我使用'for循环'来使字符串值追加类似。

datata = '<li onclick = "getset('+ data[i] +')></li>">';

在函数getset中,我希望单击发送给1个对象,例如...

{
   id: 1,
   name: "namename1",
   lname: "imlname1",
   job: "artist",
   ages: "17"
}

然后。可以在对象中使用值,例如... getData.name,getData.job,...

function getset(getData){
 getData.name = document.getElementById("txtBox").value;
}

但是..我只得到错误'Uncaught SyntaxError:Unexpected identifier'

为什么会这样?谢谢

window.onload = function () {
            data = [
                {
                    id: 1,
                    name: "namename1",
                    lname: "imlname1",
                    job: "artist",
                    ages: "17"
                }, {
                    id: 2,
                    name: "namename2",
                    lname: "imlname2",
                    job: "artist",
                    ages: "25"
                }, {
                    id: 3,
                    name: "namename3",
                    lname: "imlname3",
                    job: "artist",
                    ages: "15"
                }, {
                    id: 4,
                    name: "namename4",
                    lname: "imlname4",
                    job: "artist",
                    ages: "18"
                }, {
                    id: 5,
                    name: "namename5",
                    lname: "imlname5",
                    job: "artist",
                    ages: "27"
                }
            ];
            var datata = '';
            for (let i = 0; i < data.length; i++) {
                datata += '<li onclick="getset(' + data[i] + '  )">' + data[i].name + '</li>';
            }
     
            $("ul").append(datata);
        }

        function getset(data) {
            console.log("1");
            console.log(data);
        }
li {
            border: 1px solid #ddd;
            margin-top: -1px;
            /* Prevent double borders */
            background-color: #f6f6f6;
            padding: 12px;
            text-decoration: none;
            font-size: 18px;
            color: black;
            display: block;
            /* Make it into a block element to fill the whole list */
            position: relative;
}

li:hover {
            background-color: #adadad;
}
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TEST</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
   
</head>

<body>
    

    <input type="search" id="txtBox">
    <ul id="ulTag">

    </ul>

</body>

</html>

结果的最后,我将使文本框从“数据”中搜索数据,变量,然后单击以获取文本框的完整数据。

7 个答案:

答案 0 :(得分:1)

主要问题是因为您试图将对象附加到字符串,因此类型被强制,并且在这种情况下,所需的数据会丢失。

一种解决方法是创建要添加的jQuery对象数组,每个对象的相关对象都存储在元素的data属性中,可以轻松地从委托的事件处理程序中对其进行访问像这样的东西:

var datata = data.map(function(o) {
  return $('<li />', { text: o.name }).data('object', o);
}); 

$("ul").append(datata).on('click', 'li', function() {
  console.log($(this).data('object'));
}); 

$(function() {
  var data = [{
    id: 1,
    name: "namename1",
    lname: "imlname1",
    job: "artist",
    ages: "17"
  }, {
    id: 2,
    name: "namename2",
    lname: "imlname2",
    job: "artist",
    ages: "25"
  }, {
    id: 3,
    name: "namename3",
    lname: "imlname3",
    job: "artist",
    ages: "15"
  }];

  var datata = data.map(function(o) {
    return $('<li />', { text: o.name }).data('object', o);
  }); 
  
  $("ul").append(datata).on('click', 'li', function() {
    console.log($(this).data('object'));
  });  
});
li {
  border: 1px solid #ddd;
  margin-top: -1px;
  /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block;
  /* Make it into a block element to fill the whole list */
  position: relative;
}

li:hover {
  background-color: #adadad;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="search" id="txtBox">
<ul id="ulTag"></ul>

答案 1 :(得分:0)

您可以使用模板文字,并且需要使用JSON.stringify将对象作为参数传递。

datata += `<li onclick=getset(${JSON.stringify(data[i])})>${data[i].name}</li>`;

window.onload = function () {
            data = [
                {
                    id: 1,
                    name: "namename1",
                    lname: "imlname1",
                    job: "artist",
                    ages: "17"
                }, {
                    id: 2,
                    name: "namename2",
                    lname: "imlname2",
                    job: "artist",
                    ages: "25"
                }, {
                    id: 3,
                    name: "namename3",
                    lname: "imlname3",
                    job: "artist",
                    ages: "15"
                }, {
                    id: 4,
                    name: "namename4",
                    lname: "imlname4",
                    job: "artist",
                    ages: "18"
                }, {
                    id: 5,
                    name: "namename5",
                    lname: "imlname5",
                    job: "artist",
                    ages: "27"
                }
            ];
            var datata = '';
            for (let i = 0; i < data.length; i++) {
                datata += `
                  <li onclick=getset(${JSON.stringify(data[i])})> ${data[i].name}</li>
                `;
            }
     
            $("ul").append(datata);
        }

        function getset(data) {
            console.log("1");
            console.log(data);
        }
li {
            border: 1px solid #ddd;
            margin-top: -1px;
            /* Prevent double borders */
            background-color: #f6f6f6;
            padding: 12px;
            text-decoration: none;
            font-size: 18px;
            color: black;
            display: block;
            /* Make it into a block element to fill the whole list */
            position: relative;
}

li:hover {
            background-color: #adadad;
}
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TEST</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
   
</head>

<body>
    

    <input type="search" id="txtBox">
    <ul id="ulTag">

    </ul>

</body>

</html>

答案 2 :(得分:0)

@savecost只需替换此行,它应该可以工作。

for(让i = 0; i ” + data [i] .name +“ ”;             }

答案 3 :(得分:0)

谢谢大家的回答,并感谢Rory。我从你那里得到想法。

我了解的

。如果使用

datata = '<li onclick = "getset('+ data[i] +')></li>">';

结果是

<li onclick = "getset({id: 1,name: "namename1",lname: "imlname1",job: "artist",ages: "17"})></li>">';

然后我尝试使用。.

datata = '<li onclick="getset(data[' + i + '])">' + data[i].name + '</li>';

命令是..

getset(data[0]);

不是...

getset({id: 1,name: "namename1",lname: "imlname1",job: "artist",ages: "17"});

这也可以,但是我仍然不确定这是正确的方法。

答案 4 :(得分:0)

Rory涵盖了代码无法正常工作的原因以及jQuery的解决方法。这是使用香草JS的另一种解决方法

1)将每个对象属性作为数据属性附加到每个列表项

2)在<ul>组件中添加一个事件侦听器,而不是在每个列表项中添加一个事件侦听器,以侦听其子项在DOM(event delegation)中冒出的事件。

const data = [{"id":1,"name":"namename1","lname":"imlname1","job":"artist","ages":"17"},{"id":2,"name":"namename2","lname":"imlname2","job":"artist","ages":"25"},{"id":3,"name":"namename3","lname":"imlname3","job":"artist","ages":"15"},{"id":4,"name":"namename4","lname":"imlname4","job":"artist","ages":"18"},{"id":5,"name":"namename5","lname":"imlname5","job":"artist","ages":"27"}];

function handleClick(e) {

  // Destructure the dataset from the event target
  const { target: { dataset: { name, job, ages } } } = e;
  console.log(name, job, ages);
}

// `map`over the data and create an array of list items
const lis = data.map(obj => {
  return (
    `<li
      data-name="${obj.name}"
      data-job="${obj.job}"
      data-ages="${obj.ages}"
     >${obj.name}</li>`
  );
});

// Grab the `ul` element, add the list items to it, and add
// an event listener to listen for click events
const ul = document.querySelector('#ulTag');
ul.innerHTML = lis.join('');
ul.addEventListener('click', handleClick, false);
<ul id="ulTag"></ul>

答案 5 :(得分:-1)

datata = '<li onclick = "getset('+ data[i] +')></li>">';

应为:

datata = '<li onclick = "getset('+ data[i] +')"></li>';

答案 6 :(得分:-2)

您可以将对象作为参数。 HTML不支持具有as params对象。我修复了您的代码:

您需要通过data[i].id而不是data[i]

 for (let i = 0; i < data.length; i++) {
        datata += '<li onclick="getset(' + data[i].id + '  )">' + data[i].name + '</li>';
    }

然后通过ID从集合中检索项目:

 function getset(id) {
                        const match =  data.find(e => e.id === id);
                        console.log('Selection: ', match);
                    }

window.onload = function () {
            data = [
                {
                    id: 1,
                    name: "namename1",
                    lname: "imlname1",
                    job: "artist",
                    ages: "17"
                }, {
                    id: 2,
                    name: "namename2",
                    lname: "imlname2",
                    job: "artist",
                    ages: "25"
                }, {
                    id: 3,
                    name: "namename3",
                    lname: "imlname3",
                    job: "artist",
                    ages: "15"
                }, {
                    id: 4,
                    name: "namename4",
                    lname: "imlname4",
                    job: "artist",
                    ages: "18"
                }, {
                    id: 5,
                    name: "namename5",
                    lname: "imlname5",
                    job: "artist",
                    ages: "27"
                }
            ];
            var datata = '';
            for (let i = 0; i < data.length; i++) {
                datata += '<li onclick="getset(' + data[i].id + '  )">' + data[i].name + '</li>';
            }
     
            $("ul").append(datata);
        }

        function getset(id) {
            const match =  data.find(e => e.id === id);
            console.log('Selection: ', match);
        }
li {
            border: 1px solid #ddd;
            margin-top: -1px;
            /* Prevent double borders */
            background-color: #f6f6f6;
            padding: 12px;
            text-decoration: none;
            font-size: 18px;
            color: black;
            display: block;
            /* Make it into a block element to fill the whole list */
            position: relative;
}

li:hover {
            background-color: #adadad;
}
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TEST</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
   
</head>

<body>
    

    <input type="search" id="txtBox">
    <ul id="ulTag">

    </ul>

</body>

</html>