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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9748524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:14:30  来源:igfitidea点击:

jQuery: Get each checked radio button and append its datasrc value

jqueryappendeach

提问by jQuerybeast

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?

我做错了什么?

回答by elclanrs

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:

这是因为您在 each 内部嵌套了一个 for 循环,因此 for 循环的结果与 each 循环运行的次数一样多……尽管您不需要 for 循环,一个简单的数组并且each()可以工作:

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

回答by Didier Ghys

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

演示

回答by Simon

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

回答by devnull69

"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,标记将是非法的。