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

时间:2022-02-04 14:26:28

I am having a problem when trying to use each() twice.

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

I have a list of radio checked buttons of which each has a datasrc of a website.

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

Example:

例:

<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/>​

I want to retrieve each checked radio button so I do this:

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

$("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);                        

    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
});

Now when I retrieve every checked radio button, I want to append it with id its id and for value, its datasrc. For example:

现在,当我检索每个选中的单选按钮时,我想要将id附加为id,并将其附加到其datasrc。例如:

<div id="John">www.john.com</div>
<div id="Maria">www.maria.com</div>

When I tried using each again I get manage to get it printed but several times. For example john will print 4 times and maria will print 5 times (the amount of the id).

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

For example:

例如:

$("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);


   }

});

Will print:

将打印:

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

What I'm I doing wrong?

我做错了什么?

4 个解决方案

#1


11  

It's because you're nesting a for loop inside each so the results of the for loop run as many times as the each loop...You don't need the for loop though, a simple array and and each() will work:

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

Edit: Made it a function so you can use it at any time.

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

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(''));

#2


1  

I think your script could be overly simplified like this:

我认为您的脚本可能会过度简化,如下所示:

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

    // save for re-use
    var $this = $(this);

    // no need for jquery for javascript properties
    // 'this' is the DOM element and has a 'checked' property
    if (this.checked) {
        var src = $this.attr('datasrc');
        // you'd have to prefix the generated DIV id
        // otherwise you'll end up with duplicate IDs
        $('body').append("<div id='div" + this.id + "'>" + src + "</div>");
    }

});​

DEMO

DEMO

#3


0  

"Amount of id" makes me prick my ears. Each id may only be once on every page. If you use the same id on more than one element, the markup will be illegal.

“id的数量”让我刺痛了我的耳朵。每个id只能在每个页面上出现一次。如果您在多个元素上使用相同的ID,则标记将是非法的。

#4


0  

I solved your problem http://jsfiddle.net/3nvcj/

我解决了你的问题http://jsfiddle.net/3nvcj/

$(function() {

    $(':checked').each(function(index, element) {

        $('#result').append($('<div>').attr('id', $(element).attr('id')).text($(element).attr('datasrc')));
    });
});

#1


11  

It's because you're nesting a for loop inside each so the results of the for loop run as many times as the each loop...You don't need the for loop though, a simple array and and each() will work:

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

Edit: Made it a function so you can use it at any time.

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

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(''));

#2


1  

I think your script could be overly simplified like this:

我认为您的脚本可能会过度简化,如下所示:

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

    // save for re-use
    var $this = $(this);

    // no need for jquery for javascript properties
    // 'this' is the DOM element and has a 'checked' property
    if (this.checked) {
        var src = $this.attr('datasrc');
        // you'd have to prefix the generated DIV id
        // otherwise you'll end up with duplicate IDs
        $('body').append("<div id='div" + this.id + "'>" + src + "</div>");
    }

});​

DEMO

DEMO

#3


0  

"Amount of id" makes me prick my ears. Each id may only be once on every page. If you use the same id on more than one element, the markup will be illegal.

“id的数量”让我刺痛了我的耳朵。每个id只能在每个页面上出现一次。如果您在多个元素上使用相同的ID,则标记将是非法的。

#4


0  

I solved your problem http://jsfiddle.net/3nvcj/

我解决了你的问题http://jsfiddle.net/3nvcj/

$(function() {

    $(':checked').each(function(index, element) {

        $('#result').append($('<div>').attr('id', $(element).attr('id')).text($(element).attr('datasrc')));
    });
});