JQuery Problem With Lists
Ok, here's my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>test</title>
<style type="text/css">
.invirep{
display:none;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var replylinkcode = $('<a href="#" id="reply"> [Reply]</a>');
$('#comments ul li').append(replylinkcode);
$('#reply').click(function(){
var textareacode = $("<br/><textarea cols='10' rows='2' id='replybox'></textarea>");
$(this).parent().append(textareacode);
});
});
</script>
</head>
<body>
<div id="comments">
<ul>开发者_StackOverflow社区
<li>Comment 1</li>
<li>Comment 2</li>
<li>Comment 3</li>
<li>Comment 4</li>
</ul>
</div>
</body>
</html>
My problem is: why is it that it's only when I click the first item's reply link that the textbox appears and not for the other items (second, third and fourth items)?
Because you are using ID instead of class.
http://jsfiddle.net/a55Tb/
It looks like your appending a jQuery selector to an element.
var replylinkcode = $('<a href="#" id="reply"> [Reply]</a>');
should be:
var replylinkcode = '<a href="#" id="reply"> Reply</a>';
First, you are using a very old version of jQuery - the current version is three major versions ahead. Please upgrade, there really isn't a lot of reasons not to.
Secondly, you're creating multiple elements with the same id
- this is invalid HTML, and is probably the reason why the code does not work.
Using new syntax introduced in jQuery 1.4, you can rewrite the code as such:
$('<a>', {
text: '[reply]',
href: '#',
click: function(){
$("<br/><textarea cols='10' rows='2' id='replybox'></textarea>").appendTo(this.parentNode);
}
}).appendTo('#comments li');
精彩评论