我有这个 fiddle
http://jsfiddle.net/nesreen/m5TMF/763/
$("#AddansId").click(function(){
//get the parent of the div with id(Collapse+x)
// to abend the data content of the textarea beside the word
//Account Registeration at PrepBootstrap
});
我可以创建一个带有按钮的动态 Accordion 在每个 Accordion 内部,我需要创建另一个文本区域和按钮,以在同一个折叠中添加其他文本 但我面临的问题是如何每次都能获取按钮的父级,即使父级 id 也是动态的
最佳答案
让我们看看。这里需要采取几个步骤:
首先,在这种情况下,您需要稍微不同地绑定(bind)点击( event delegation ),因为您想要动态点击 添加的元素
其次,我们使用
closest()
获取父ID方法和attr('id')
获取
textarea
你可以使用的值(value)$(this).parent().prev().find('textarea').val()
然后使用
append()
方法将文本附加到您想要的单词旁边,最后使用$(this).closest('.container').append(answer);
在单词之前添加文本(这有点不清楚,所以我在Account Registeration at PrepBootstrap
之前添加了它。我希望这就是你的意思)
var x = 1;
$(document).on('click', "#AddansId", function() {
var idOfParent = $(this).closest('.panel-collapse').attr('id');
//console.log(idOfParent);
var answer = $(this).parent().prev().find('textarea').val();
$(this).closest('.container').append(answer);
});
$(document).on('click', '#AddQuestId', function() {
x = x + 1;
$("#accordion").append('<div class="panel panel-default">' +
'<div class="panel-heading">' +
'<h4 class="panel-title"> ' +
'<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse' + x + '">' + $("#comment").val() + '</a> </h4>' +
'</div>' +
'<div id="collapse' + x + '" class="panel-collapse collapse in">' +
'<div class="panel-body">' +
'<div class="container"> ' +
' <form>' +
'<div class="form-group" >' +
'<label for="comment">answer:</label>' +
'<textarea class="form-control" rows="5" id="answer' + x + '"></textarea> ' +
' </div>' +
' <div style="float: right;"> <input type="button" class="btn btn-info" value="answer" id="AddansId"></div>' +
'</form>' +
'</div>' +
'Account registration at <strong>PrepBootstrap</strong>' +
'</div>' +
'</div>' +
'</div>' +
'</h4>' +
'</div>');
});
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="container">
<form>
<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<div style="float: right;"> <input type="button" class="btn btn-info" value="Add Question" id="AddQuestId"></div>
</form>
</div>
<div class="panel-group" id="accordion">
</div>
关于javascript - 动态 Accordion 帖子和答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42811649/