2013-10-17 26 views
3

我試圖創建使用jQuery的選擇框,但鏈接隨機填充,所以我需要循環通過鏈接並抓住它使選擇框,這裏是我的代碼任何想法如何使用短手/循環?由於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(); 

Fiddle

回答

4
var $this = $(this); 

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

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

1

無需除非喲功能你打算將它用於嚴重下落。

var ddl = $("#select"); 

$("p a").each(function() { 
    var link = $(this); 
    ddl.append($("<option></option>").val(link.text()).html(link.text())); 
}); 
3

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

詹姆斯蒙塔涅的回答的更清潔和更jQuery的取向溶液

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

或與特性映射的替代:

$this.append($("<option/>", { 
    value: '', 
    text: $(this).text() 
})); 
2
$('#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); 

}); 
}