JQuery实现选择特定楼层回复
需求:
一个论坛里面的小功能,除了回复帖子之外,也可以回复帖子下面的回复。具体实现细节:
- 每一个回复有一个“回复”按钮,点击按钮实现:
- 在form表单里面加入一个input元素,内容是需要回复的楼层数,这样post过去之后才能在后台处理;
- 在回复内容的textarea里面加入文字“回复x楼:”
接下来就是具体实现了,无疑只能用JS_(:з」∠)_,又是每次到了这时候才临时各种百度怎么用…
获取楼层数
在button上绑定了一个function
<button class="btn btn-primary" onclick="cause_reply(this)">回复</button>
<p>{{reply.floor_num}}楼 {{reply.author.username}} at {{reply.time}}</p>
最开始我没有放this在里面,只是写了个方法,后来发现这样的话不同的楼层结构都是类似的,没有办法获取到楼层数,只能用this确定button的具体位置,然后从button找到楼层数。
实际上只用了一行,思路是获取button的兄弟元素p然后截取字符串,用原生js的时候一直出问题,nextSibling获取到的是[object text],然后这个text的内容又显示不出来,后来百度了半天可能是firefox的原因,把button后面的换行也作为一个元素,于是就获取不到内容,最后用jquery解决了。
var reply_floor=$(obj).next().text().substr(0,1);
form的结构:
<form class="form-horizontal panel col-md-10 col-md-offset-1 container" method="POST" action="/forum/post/">{% csrf_token %}
<div class="form-group col-md-12">
<label class="control-label" for="exampleContent"></label>
<br/><br/>
<textarea rows="6" name="content" class="form-control" id="exampleContent" placeholder=""></textarea>
</div>
<div class="form-group col-md-4" id="post_field">
<input type="hidden" name="post_type" value="post_reply"/>
<input type="hidden" name="post_id" value="{{post.id}}"/>
<input type="submit" class="btn btn-lg btn-primary" value="回帖"/>
</div>
</form>
添加文字内容
同样一行解决:
$("textarea").append("回复"+reply_floor+"楼:");
增加input元素
var new_inp=document.createElement("input");
new_inp.setAttribute("type", "hidden");
new_inp.setAttribute("id", "reply_id");
new_inp.setAttribute("name", "reply_id");
new_inp.setAttribute("value", reply_floor);
$('#post_field').append(new_inp);
差不多就是这样,然后还有一个就是,如果先点击过一个楼层的回复,又点击了另外一个楼层,相应的前一个就要清除掉,改成最后操作的楼层。所以加了一个判断过程,最后全部代码是这样:
function cause_reply(obj){
if($("#reply_id").length>0){
$("#reply_id").remove();
$("textarea").empty();
}
var new_inp=document.createElement("input");
var reply_floor=$(obj).next().text().substr(0,1);
new_inp.setAttribute("type", "hidden");
new_inp.setAttribute("id", "reply_id");
new_inp.setAttribute("name", "reply_id");
new_inp.setAttribute("value", reply_floor);
$('#post_field').append(new_inp);
$("textarea").append("回复"+reply_floor+"楼:");
}