1

如何使用此代码获取 li-item 的选定类?

现在它循环 ul 中的所有类,而不仅仅是选定的。

$('<div id="chooseCustomFields'
  + field_id
  + '" class="wrapper-customfields" tabindex="1"><span>Choose Type</span>'
  + '<ul id="chooseCustomField'
  + field_id
  + '" class="dropdown">'
  + '<li class="chooseCheckbox"><i class="fa-icon-check"></i>Checkbox</li>'
  + '<li class="chooseAlternatives"><i class="fa-icon-list-ul"></i> Alternatives</li>'
  + '<li class="chooseDropdown"><i class="fa-icon-list-alt"></i> Dropdown</li>'
  + '<li class="chooseTextField"><i class="fa-icon-font"></i> Text</li>'
  + '</ul></div>').appendTo(field_secondchild).addClass("metro three-d")
.click(function() {
$('#chooseCustomField' + field_id + ' li').each(function() {
    alert($(this).attr('class'))
});
}); 
4

2 回答 2

1

看起来你想要点击li

$('<div id="chooseCustomFields'
  + field_id
  + '" class="wrapper-customfields" tabindex="1"><span>Choose Type</span>'
  + '<ul id="chooseCustomField'
  + field_id
  + '" class="dropdown">'
  + '<li class="chooseCheckbox"><i class="fa-icon-check"></i>Checkbox</li>'
  + '<li class="chooseAlternatives"><i class="fa-icon-list-ul"></i> Alternatives</li>'
  + '<li class="chooseDropdown"><i class="fa-icon-list-alt"></i> Dropdown</li>'
  + '<li class="chooseTextField"><i class="fa-icon-font"></i> Text</li>'
  + '</ul></div>').appendTo(field_secondchild).addClass("metro three-d")
.on('click', 'li', function() {
    alert($(this).attr('class'))
});
于 2013-05-07T13:56:22.630 回答
0

你的 html 的格式很差,所以我修复了这个问题,然后我将 html 和 js 分开,这样我们就可以看到它确实有效。

这是工作小提琴:http:
//jsfiddle.net/acturbo/LmXz4/1/

javascript:

var field_id = "#chooseCustomField" + "555";
var field_secondchild = "#secondchild";

// new logic
$(field_id).appendTo( field_secondchild ).addClass( "metro three-d");

// easier way to assign a click event to each li
$(field_id + ' li').on("click", function() {
    alert($(this).attr('class'))
});

html(测试所需)

<div id="secondchild">
    <p>for testing only</p>
</div>
<div>
    <p>should be last</p>
</div>

<div id="chooseCustomFields555" class="wrapper-customfields" tabindex="1">
  <span>Choose Type</span>
  <ul id="chooseCustomField555" class="dropdown">
    <li class="chooseCheckbox"><i class="fa-icon-check"></i>Checkbox</li>
    <li class="chooseAlternatives"><i class="fa-icon-list-ul"></i> Alternatives</li>
    <li class="chooseDropdown"><i class="fa-icon-list-alt"></i> Dropdown</li>
    <li class="chooseTextField"><i class="fa-icon-font"></i> Text</li>
    </ul>
</div>
于 2013-05-07T14:13:29.123 回答