5

我正在尝试使用 jquery 创建选择框,但链接是随机填充的,所以我需要通过链接循环并抓住它来制作选择框,这是我的代码,知道如何使用简写/循环吗?谢谢

HTML:

<p>
    <a href="#">option1</a>
    <a href="#">option2</a>
    <a href="#">option3</a>
</p>

<select  id="select"></select>

JS:

$.fn.populate = function() {
    var option1 = $('p a:eq(0)').text();
    var option2 = $('p a:eq(1)').text();
    var option3 = $('p a:eq(2)').text();
  $(this)
    .append('<option value="">' + option1 + '</option>')
    .append('<option value="">' + option2 + '</option>')
    .append('<option value="">' + option3 + '</option>')
}

$('#select').populate();

小提琴

4

6 回答 6

7
var $this = $(this);

$('p a').each(function(){
    $this.append('<option value="">' + $(this).text() + '</option>');
});

http://jsfiddle.net/QgCqE/1/

于 2013-10-17T20:11:46.940 回答
4

http://jsfiddle.net/kasperfish/RY3U9/4/

var selectbox=$("#select");//cache our slectbox, so jquery doesn't have to look for it in every loop.

$('p > a').each(function(){//select all a tags in p (loop through them)
    var text=$(this).text();//cache the link text in a variable because we need it twice.
    selectbox.append($('<option>').text(text).val(text));//add new option with value en text to selectbox
})
于 2013-10-17T20:25:33.287 回答
4

James Montagne的答案的更清洁和更面向 jQuery 的解决方案:

$this.append( $('<option/>').val('').text($(this).text()) );

或具有属性映射的替代方案:

$this.append($("<option/>", {
    value: '',
    text: $(this).text()
}));
于 2014-11-28T15:09:46.253 回答
3
$('#new_organizations').click(loadOrgTypes);

function loadOrgTypes() {

  console.log('retrieving all Org Types');
  $.ajax({
    type: 'GET',
    url: rootURL+'org_types',
    dataType: "json", // data type of response
    success: renderOrgTypes,

     error: function(err){
       console.log('Error');
       console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
                        }

  });
}


function renderOrgTypes(data){
 var list = data == null ? [] : (data instanceof Array ? data : [data]);

 var select = $("#org_types_select");
    select.empty();

 $.each(list , function(index, org_types) {
            var content='<option org_type_id="' + org_types.id + '">' + org_types.name_loc + '</option>';
            select.append(content);

 });
}
于 2015-07-14T09:47:55.433 回答
1

除非您打算将其用于服务器下拉菜单,否则不需要功能。

var ddl = $("#select");

$("p a").each(function () {
    var link = $(this);
    ddl.append($("<option></option>").val(link.text()).html(link.text()));
});
于 2013-10-17T20:17:32.693 回答
1

要使元素中的循环使用$.each


除非你想让它可重用,否则你不需要扩展 jQuery。

LIVE DEMO

$.fn.populate = function(el) {
    var options = '';
    $(el).each(function(i, e) {
       options += '<option>' + $(this).text() + '</option>'; 
    });
    this.append(options);
    return this;
}

$('#select').populate('p > a');
于 2013-10-17T20:28:02.563 回答