jQuery获取href值并插入下拉菜单

时间:2012-08-22 13:18:48

标签: jquery

我有以下自动生成的代码,我希望jQuery代码帮助我取出每个href的值(部分:“/ listing-agent-staff / barack-obama”),以及将此值插入下拉菜单。

自动生成的代码:

<div class="StaffBlock StaffName">
<a href="/listing-agent-staff/barack-obama">Barack Obama</a>
</div>
<div class="StaffBlock StaffName">
<a href="/listing-agent-staff/bill-clinton">Bill Clinton</a>
</div>
<div class="StaffBlock StaffName">
<a href="/listing-agent-staff/will-smith">Will Smith</a>
</div>

下拉菜单我希望将值插入到:

<label for="CAT_Custom_231994">Listing Contact</label>
<select name="CAT_Custom_231994" id="CAT_Custom_231994" class="cat_dropdown">
<option value="">-- Please select --</option>
<option value="/listing-agent-staff/barack-obama">Barack Obama</option>
<option value="/listing-agent-staff/bill-clinton">Bill Clinton</option>
<option value="/listing-agent-staff/will-smith">Will Smith</option>
</select>

请注意第一部分是自动生成的,因此记录数量会有所不同,第二部分中的选项数量应该与之相应。

3 个答案:

答案 0 :(得分:3)

这应该这样做:

$(".StaffBlock.StaffName a").each(function() {
    $(".cat_dropdown").append($("<option/>", {
        value: $(this).attr("href"),
        text: $(this).text()
    }));
});​

请参阅DEMO

答案 1 :(得分:0)

容器周围是否有容器?如果是,您可以像var

一样轻松地遍历它们

$('#id_of_main_container").children().each(function (e) { $(this).find('a').attr('href'); }

使用html(),您可以使用href-Values轻松构建-Tags数组并构建自定义树。

答案 2 :(得分:0)

这样的事情应该有效:

$(document).ready(function() {
    var select = $('<select name="CAT_Custom_231994" id="CAT_Custom_231994" class="cat_dropdown"><option value="">-- Please select --</option></select>');
    $('div.StaffBlock.StaffName a').each(function() {
        select.append('<option value="'+ $(this).attr('href') +'">'+ $(this).text() +'</option>');
    });
    $('div.StaffBlock.StaffName').last().after(select).after('<label for="CAT_Custom_231994">Listing Contact :</label>');
});​

这是JSFiddle

相关问题