jQuery:获取每个选中的单选按钮并附加其datasrc值

jQu*_*ast 1 each jquery append

尝试使用each()两次时遇到问题.

我有一个无线电检查按钮列表,每个按钮都有一个网站的数据库.

例:

<input type="radio" checked datasrc="www.john.com" id="John">John<br/>
<input type="radio" checked datasrc="www.maria.com" id="Maria">Maria<br/>
<input type="radio" datasrc="www.joe.com" id="Joe">Joe<br/>?
Run Code Online (Sandbox Code Playgroud)

我想检索每个选中的单选按钮,所以我这样做:

$("input:radio").each(function(){

var name = $(this).attr("id");


    if($("[id="+name+"]:checked").length == 1)
    {
        var src = $('#' + name).attr("datasrc")                                                                                                                                                                                                                                                                                                                                                                                                                                                                     

      console.log(name);
      console.log(src);                        

    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
});
Run Code Online (Sandbox Code Playgroud)

现在,当我检索每个选中的单选按钮时,我想要将id附加为id的id和value,以及它的datasrc.例如:

<div id="John">www.john.com</div>
<div id="Maria">www.maria.com</div>
Run Code Online (Sandbox Code Playgroud)

当我再次尝试使用它时,我设法将它打印出来但是好几次.例如,john将打印4次,maria将打印5次(id的数量).

例如:

$("input:radio").each(function () {

   var name = $(this).attr("id");

   if ($("[id=" + name + "]:checked").length == 1) {
      var src = $('#' + name).attr("datasrc")

      var html = "";
      for (i = 0; i < name.length; i++) {
         html += "<div id='" + name + "'>" + src + "</div>"
      }

      $("body").append(html);


   }

});
Run Code Online (Sandbox Code Playgroud)

将打印:

www.john.com
www.john.com
www.john.com
www.john.com
www.maria.com
www.maria.com
www.maria.com
www.maria.com
www.maria.com
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

elc*_*nrs 11

这是因为你在每个循环中嵌入一个for循环,所以for循环的结果运行的次数与每个循环一样多......你不需要for循环,一个简单的数组,并且each()可以工作:

编辑:使它成为一个功能,以便您可以随时使用它.

var getUrls = function () {

    var urls = [];

    $('input:radio').each(function () {

        var $this = $(this),
            id = $this.attr('id'),
            url = $this.attr('datasrc');

        if ($(this).prop('checked')) {
            urls.push('<div class="' + id + '">' + url + '</div>');
        }

    });

    return urls;

};

$('body').append(getUrls().join(''));
Run Code Online (Sandbox Code Playgroud)