找到complexe jquery选择器

时间:2014-03-22 20:13:53

标签: jquery html

我不是Jquery的专家。我想获取特定父选择器的ID。

我的页面包含以下内容

<p>
getting this    <input id="comment16" type="button" value="Comment" disabled="">
                <div class="form" style="">
                    <form id="comment-form" method="post" action="/post/index.php/comment/create?post_id=16">
                        <p class="note">Fields with <span class="required">*</span>are required.</p>
                        <div id="comment-form_es_" class="errorSummary" style="display:none">
                            <p>Please fix the following input errors:</p>
                            <ul><li>dummy</li></ul>
                        </div>
                        <div class="row">
                            <label class="required" for="comment_comment">  Comment
                                <span class="required">*</span>
                            </label>
                            <input id="comment_comment" type="text" name="comment[comment]" maxlength="140" size="60">
                            <div id="comment_comment_em_" class="errorMessage" style="display:none"></div>
                        </div>
                        <div class="row buttons">
From here                   <p> <input id="save" type="button" value="Create"> </p>    
                            <p> <input id="cancelcomment" type="button" value="Cancel"></p>
                        </div>
                    </form>
                </div>
</p>

我试过这个

$('body').on('click','#save',function(e) {
            var $thisClicked = $(this);
            var parameter = $thisClicked.attr("id");
            $("#comment-form").submit(function(e) {
                var postData = $(this).serializeArray();
                var parameter = $thisClicked.parent('div').parent('form').parent('div').closest('input').attr('id');
                parameter = parameter.replace('comment','');

....
你能帮帮我吗? 提前谢谢

2 个答案:

答案 0 :(得分:0)

$('#save').click(function() {
  var $this = $(this);
  // Gets the closest element in the ancestry matching the selector
  var $form = $this.closest(".form");
  // Gets the preceding sibling element
  var $commentInput = $form.prev();
  alert($commentInput.attr("id"));
});

closest docs | prev docs

很酷的东西。我大多只是用谷歌搜索它

答案 1 :(得分:0)

您无需在按钮单击尝试中执行表单提交:

$('#save').click(function() {
  var $this = $(this);
  $form = $this.closest(".form"); 
  $commentInput = $form.prev();   
    parameter = $commentInput.children().attr('id');
    parameter = parameter.replace('comment','');
    alert(parameter);
});

Fiddle

否则,您可以在表单提交上绑定您的活动,然后您必须更改您的按钮类型以提交。