这是我的代码:
$(".cbtn").click(function(e) {
alert("here");
var id = $(this).attr('id');
var comment = $('input[id$=id]').val();
alert("hay" + id);
alert(comment);
$.post("comments.php", {
id: id,
comment: comment
})
});
});
Run Code Online (Sandbox Code Playgroud)
的idof cbtn和文本字段是动态创建的,如下所示:
<input type="text" class="enter_comment value="comments" id="comm<?php echo $row['p_id'];?>"/>
<input type="button" value="enter" class="cbtn" id="<?php echo $row['p_id'];>">
Run Code Online (Sandbox Code Playgroud)
当cbtn被点击时,我想要得到的id文本字段具有相同ID的目的cbtn。但是它正在返回undefined。
您需要id在选择器中连接变量,如下所示:
$(".cbtn").click(function(e) {
var id = this.id;
var comment = $('input[id$=' + id + ']').val();
$.post("comments.php", {
id: id,
comment: comment
})
});
Run Code Online (Sandbox Code Playgroud)
另外,由于id文本字段的与复选框相同,但是带有comm前缀,您可以id直接选择它,这样会更快:
var comment = $('#comm' + id).val();
Run Code Online (Sandbox Code Playgroud)
或者,如果文本字段始终是复选框前面的元素,则可以id完全不需要通过选择来使用prev()方法:
$(".cbtn").click(function(e) {
$.post("comments.php", {
id: this.id,
comment: $(this).prev().val()
})
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
615 次 |
| 最近记录: |