使用.each(),我想.bpend()一个数字值到.Query中的的值.attr()ibute

时间:2022-10-18 19:15:57

I want to put numbers separated by a comma in the value attribute of an <input>. The problem is it erases it and puts a new number there instead of appending it to the end of the attribute. Can anyone help here???

我想在的value属性中用逗号分隔数字。问题是它会删除它并在其中放入一个新数字,而不是将其附加到属性的末尾。谁能帮到这里???

What you won't see in this html is what the JQuery UI builds when something is dropped in to the div. The list element will look like this:

你不会在这个html中看到的是JQuery UI在将某些内容放入div时构建的内容。 list元素如下所示:

<li>Doe, John, 12787</li>
<li>Doe, Jane, 9867</li>
<li>etc...

I have extracted the number in the list element and I need to build an array of some sort then make the array of numbers the value attribute for the

我已经在list元素中提取了数字,我需要构建一个类型的数组,然后使数字数组成为值的属性

The html:

<div id="teamPool">
    <h1 class="ui-widget-header">Your Branch Team</h1>
    <div class="ui-widget-content">
        <ol>
            <li class="placeholder">Add your items here</li>
        </ol>
    </div>
</div>

<div id="remove"><p>Remove</p></div>
<div id="clear"><p>Clear</p></div>
<div id="submit"><p>Submit</p></div>    

    <!--- Hidden variables --->
<div id="hiddenVariables">
    <cfoutput>
        <input type="hidden" name="uid" value="1" />
        <input id="eids" type="hidden" name="eid" value="" />
    </cfoutput>
</div>

The JS:

$('#submit').click(function(){
   $('#teamPool li').each(function() {
      var num = parseInt($(this).text().match(/\d+/)[0], 10);
      var strv = num+' ,';
      $('#eids').attr('value',strv);
   });
});

1 个解决方案

#1


2  

You should join them outside of the each, calling .attr just once

你应该在每个人之外加入他们,只需要调用一次.attr

$('#submit').click(function(){
   var nums = [];
   $('#teamPool li').each(function() {
      var num = parseInt($(this).text().match(/\d+/)[0], 10);
      nums.push(num);
   });
   var strv = nums.join(', ');
   $('#eids').attr('value',strv);
});

#1


2  

You should join them outside of the each, calling .attr just once

你应该在每个人之外加入他们,只需要调用一次.attr

$('#submit').click(function(){
   var nums = [];
   $('#teamPool li').each(function() {
      var num = parseInt($(this).text().match(/\d+/)[0], 10);
      nums.push(num);
   });
   var strv = nums.join(', ');
   $('#eids').attr('value',strv);
});