finished asking the question but cant post because Q does not meet requirements please ignore this attempt to fill white space
我想要打印任何有他们班级选择的项目的文本"使用jQuery。我怎样才能做到这一点?
我需要用逗号分隔打印文本。
答案 0 :(得分:1)
您可以使用jQuery.each()功能。
例如:
$( document ).ready(function() {
var items = '';
$( "li.selected" ).each(function( index ) {
items+=$(this).text()+',';
});
$('#specialitycenters').after('<span>'+items.slice(0,-1)+'</span>');
});
示例here。希望它有所帮助。
已更新,以包含<span>
代码。
答案 1 :(得分:0)
您可以使用jQuery选择所有带有“selected”类的lis,然后使用jQuery each()方法循环遍历它们并将它们附加到您需要的任何位置。您可以使用text()方法从元素中获取文本,如循环中所示。
我们还检查我们是否在循环的最后一个索引处,以了解是否包含逗号和空格。
$(document).ready(function() {
// get all of the li elements with the class selected and declare
// our text variable
var selected = $("li.selected");
var text;
// loop over our lis and do whatever you need with them
$.each(selected, function(index) {
// add the comma as long as it isn't the last one in the set
if (index === (selected.length - 1)) {
text = $(this).text();
} else {
text = $(this).text() + ", ";
}
// append the result to wherever you need, in this
// case it would just append it to the body
$("body").append(text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="specialitycenters" class="specialitycenters" name="specialty-centers">
<li class="selected">ARCH At Risk Children Center</li>
<li class="selected">ARMS Primary care services for HIV AIDS</li>
<li class="selected">Adolescent - Young Adult Medicine</li>
<li>After the Cancer Experience ACE Late Effects Clinic Long Term Followup</li>
<li>Allergy</li>
<li>Allergy and Immunology</li>
<li>Analytical Imaging Modeling Center AIM</li>
<li>Anesthesiology</li>
<li>Comprehensive Stone Program</li>
</ul>