【问题标题】:remove the div above删除上面的div
【发布时间】:2012-12-09 00:19:33
【问题描述】:

我有一个看起来像这样的模板。

示例模板

<div id="form-entry">
    <h4>Some heading here</h4>
    <div class="form-field">
        <label>Some Label</label>
        <input type="text" class="some_text" />
    </div>
    <div class="form-field">
        <label>Some Label</label>
        <input type="text" class="some_text" />
    </div>
    <div class="form-field">
        <label>Some Label</label>
        <input type="text" class="some_text" />
    </div>
    <div class="form-field">
        <input type="checkbox" />
        <label>Some Label</label>
    </div>
    <div class="form-field">
        <label>Some Label</label>
        <textarea></textarea>
    </div>
</div>

如果用户选中复选框,我想删除(或隐藏)包含 checkbox 输入的 div 上方的 form-field div。 HTML 是自动呈现的,没有任何特定的id'sclasses。我该怎么做。 jQuery 的位置会有用吗?

JS

$('.form-field input[type=checkbox]').click( function(){
    entity = $(this);
    dad = entity.parent(); // This gets the form-field div element that contains the checkbox
}); 

如何捕获dad 元素上方的form-field div 元素?

【问题讨论】:

  • 你不能在复选框前的框中添加一个 id 吗?抱歉,请重新阅读您的问题。你说你不能
  • entity.parent().parent(); ?
  • 当我提到模板是自动呈现的,我真的不能。我也忘了提到我在同一页面上也有一些类似的div.form-entry

标签: jquery html hide


【解决方案1】:
$('.form-field input[type=checkbox]').on('change', function(){
    if (this.checked) 
        $(this).closest('.form-field').prev().remove();
}); 

删除包含复选框的.form_field 上方的.form_field(如果已选中)?

【讨论】:

  • 不需要检查是否被检查:如果它从初始(未检查)状态发生变化,则必须检查。
  • @dystroy - 是的,你可能是对的,我确实考虑过,但检查无关紧要,并显示如果将初始状态更改为检查或类似的情况如何检查.
  • 我不确定我是否喜欢 gdoron 的最后一次编辑。 adeneo 的版本对我来说很好。
【解决方案2】:

你可以这样做

$('#form-entry input[type="checkbox"]').change(function(){
    $(this).parent().prev().remove();
});

Demonstration

【讨论】:

    【解决方案3】:

    您可以使用以下 jQuery:

    $('.form-field input[type=checkbox]').click(function() {
        $(this).parent().prev().toggle(); // parent is the checkboxs div, prev returns the previous element in the DOM
    });​
    

    Toggle 将在每次单击复选框时隐藏/显示前一个 div。

    这是一个jsFiddle,它显示了它是如何工作的

    【讨论】:

      【解决方案4】:
      $('.form-field input[type=checkbox]').click( function(){
          entity = $(this);
          dad = entity.parent().prev().remove(); // This gets the form-field div element that contains the checkbox
      }); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-26
        • 2013-11-24
        • 2020-12-25
        相关资源
        最近更新 更多