我正在尝试使用jQuery根据<li>
<ul>
中的文字向<h3>
添加新的<ul>
我在页面上有几个<h3>
和无序列表。
列出HTML:
<h3 class="category">
Interactive Learning
</h3>
<ul>
<li><a href="http://ocw.mit.edu/courses/#electrical-engineering-and-computer-science">MIT Open Courseware</a></li>
<li><a href="http://www.codecademy.com/#!/exercises/0">Codecademy</a></li>
<li><a href="https://p2pu.org/en/schools/school-of-webcraft/">P2PU: School of Webcraft</a></li>
<li><a href="https://www.coursera.org/category/cs-programming">Coursera</a></li>
<li><a href="http://www.udacity.com/">Udacity</a></li>
<li><a href="http://code.google.com/edu/">Google Code University</a></li>
<li><a href="https://developer.mozilla.org/en-US/learn">Mozilla Developer Network</a></li>
</ul>
表单HTML:
<form id="addRec_form" action="classes/resources/addResource.php" method="post">
<p><select name="categoryList" id="categoryList">
<option value="0">Select a category to add to</option>
<?php
$categories = array(
1 => "Microsoft Dreamspark",
"Video Tutorials",
"Interactive Learning",
"Language Documentation",
"IDEs and Text Editors",
"Additional Tools and Resources"
);
for ($i = 1; $i <= 6; $i++)
print "<option value=\"$i\">$categories[$i]</option><br />";
?>
</select></p>
<p>Resource name: <input type="text" name="recName" id="recName" /></p>
<p>Resource URL: <input type="text" name="recURL" id="recURL" /></p>
<p><input type="submit" name="submitAddRec" value="Add resource" id="submitAddRec" /></p>
</form>
jQuery的:
$.ajax ({
type: 'post',
url: '/classes/resources/addResource.php',
data: {
recName: $('#recName').val(),
recURL: $('#recURL').val()
},
success: function(data) {
if (data === 'added') {
$('h3.category').each( function() {
var cate = $('#categoryList option:selected').text();
var title = $('#recName').val();
var url = $('#recURL').val();
var newListItem = '<li><a href=\"' + url + '\">' + title + '</a></li>';
if ($(this).text() == cate) {
$(this).next('ul').append(newListItem);
$('ul').listview('refresh');
}
});
$('span#resError').fadeIn(400).text('Resource added successfully. Add another?');
}
else
$('span#resError').fadeIn(400).text('There was an error adding this resource');
}
});
但<ul>
没有添加任何内容。有什么想法吗?
答案 0 :(得分:0)
使用.next()
代替.closest()
( ul
位于h3
旁边)
$(this).next('ul').append(newListItem);