jQuery查找前面的元素?

11

当我想要查找一个对象的子元素时,可以使用children(); 当我想要在另一个对象内部查找一个对象,不一定是它的子元素时,可以使用find()。 如果我想要找到父对象,我使用parent(), 但如果我想要找到先辈对象,并且不知道它是父亲、祖父母还是曾祖父母,我该怎么做呢?

我举个例子:我正在构建一个插件,该插件将应用于一些'input:text'。

最终,我需要对包含它们的表单执行某些操作。 但有时,文本框将直接位于表单内,或者它们可能位于无序列表或表格内。

我能以一般的方式引用表单吗?

3个回答

19
你可以使用jQuery的closest()方法:
$('input:text').change(
function(){
    var ancestorFormElement = $(this).closest('form');
    // do stuff.
});

$('input:text').change(function() {
  var ancestorFormElement = $(this).closest('form');

  ancestorFormElement.addClass('hasInputChanged');
});
form {
  border: 2px solid #000;
  padding: 1em;
}
form.hasInputChanged {
  border-color: limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
  <fieldset>
    <legend>Simple demo</legend>
    <label for="name">Text Input:</label>
    <input type="text" name="name" id="name" value="" tabindex="1" />
  </fieldset>
</form>

外部 JS Fiddle演示,用于实验或开发。

或者,您可以使用DOM方法,将 <form> 元素与其后代表单元素 (<input /><textarea><select> 等) 相关联:

$('input:text').change(function() {
  var ancestorFormElement = this.form;

  // because 'this.form' returns a DOM node, it
  // must be converted to a jQuery object in 
  // order to utilise jQuery methods:
  $(ancestorFormElement).addClass('hasInputChanged');
});

$('input:text').change(function() {
  var ancestorFormElement = this.form;

  $(ancestorFormElement).addClass('hasInputChanged');
});
form {
  border: 2px solid #000;
  padding: 1em;
}
form.hasInputChanged {
  border-color: limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
  <fieldset>
    <legend>Simple demo</legend>
    <label for="name">Text Input:</label>
    <input type="text" name="name" id="name" value="" tabindex="1" />
  </fieldset>
</form>

外部JS Fiddle demo,用于实验或开发。

此外,因为我强烈怀疑您想要的更改(无论是什么)在“更改”被撤消时应恢复,所以建议采用以下方法:

$('input:text').change(function() {
  var ancestorFormElement = this.form;

  // here we use the 'toggleClass(<class-name>, <switch>)'
  // method; where the 'switch' returns a Boolean true/false
  // if it evaluates to true then the class-name is added
  // and if it evaluates to false then the class-name is
  // removed:
  $(ancestorFormElement).toggleClass('hasInputChanged', this.value !== this.defaultValue);
});

$('input:text').change(function() {
  var ancestorFormElement = this.form;

  $(ancestorFormElement).toggleClass('hasInputChanged', this.value !== this.defaultValue);
});
form {
  border: 2px solid #000;
  padding: 1em;
}
form.hasInputChanged {
  border-color: limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
  <fieldset>
    <legend>Simple demo</legend>
    <label for="name">Text Input:</label>
    <input type="text" name="name" id="name" value="" tabindex="1" />
  </fieldset>
</form>

用于实验或开发的外部JS Fiddle演示

另外,完全可以将change事件处理程序委托给<form>元素本身,使用on()

$('form').on('change', function(e) {

  // here 'e' is the event-object passed to the
  // event-handling function; 'e.target' is the
  // element that received the initiating event:
  var changedEl = e.target;

  $(this).toggleClass('hasInputChanged', changedEl.value !== changedEl.defaultValue);
});

$('form').on('change', function(e) {
  var changedEl = e.target;

  $(this).toggleClass('hasInputChanged', changedEl.value !== changedEl.defaultValue);
});
form {
  border: 2px solid #000;
  padding: 1em;
}
form.hasInputChanged {
  border-color: limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
  <fieldset>
    <legend>Simple demo</legend>
    <label for="name">Text Input:</label>
    <input type="text" name="name" id="name" value="" tabindex="1" />
  </fieldset>
</form>

外部JS Fiddle演示, 用于实验或开发。

也可以将选择器传递给on()方法,以指定应该启动给定事件(这里是“change”事件)并触发绑定到祖先的事件处理程序的元素:

// here we pass the selector, 'input[type=text]' to the
// method, which restricts the event-handling to only
// those events originating with <input> elements whose
// 'type' attribute is equal to 'text':
$('form').on('change', 'input[type=text]', function(e) {

  $(this).toggleClass('hasInputChanged', changedEl.value !== changedEl.defaultValue);
});

$('form').on('change', 'input[type=text]', function(e) {
  var ancestorFormElement = this.form;

  $(ancestorFormElement).toggleClass('hasInputChanged', this.value !== this.defaultValue);
});
form {
  border: 2px solid #000;
  padding: 1em;
}
form.hasInputChanged {
  border-color: limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
  <fieldset>
    <legend>Simple demo</legend>
    <label for="name">Text Input:</label>
    <input type="text" name="name" id="name" value="" tabindex="1" />
  </fieldset>
</form>

外部 JS Fiddle演示,用于实验或开发。

最后,一种使用普通JavaScript实现相同行为的方法:

// defining a named function to handle the
// event-handling, the 'event' argument is
// passed automagically from the
// addEventListener() method (below):
function changeHandler(event) {

  // 'this' is the element to which
  // event-handler was bound (again
  // automagically passed from
  // addEventListener()):
  var form = this,
    changed = event.target;

  // here we use the Element.classList API; which
  // works much as toggleClass() does, adding the
  // supplied class-name if the switch that follows
  // evaluates to true, removes it if the switch
  // evaluates to false:
  form.classList.toggle('hasInputChanged', changed.value !== changed.defaultValue);

}

// retrieving the <form> element using
// document.querySelector(), which returns
// the first element in the document that
// matches the CSS selector passed to the
// function:
var formElement = document.querySelector('form');

// using addEventListener to bind the named 
// function (changeHandler) as the event-
// handler for the 'change' event:
formElement.addEventListener('change', changeHandler);

function changeHandler(event) {
  var form = this,
    changed = event.target;

  form.classList.toggle('hasInputChanged', changed.value !== changed.defaultValue);

}

var formElement = document.querySelector('form');

formElement.addEventListener('change', changeHandler);
form {
  border: 2px solid #000;
  padding: 1em;
}
form.hasInputChanged {
  border-color: limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
  <fieldset>
    <legend>Simple demo</legend>
    <label for="name">Text Input:</label>
    <input type="text" name="name" id="name" value="" tabindex="1" />
  </fieldset>
</form>

外部 JS Fiddle演示,用于实验或开发。

参考资料:


2
“我不完全确定您的问题是什么,因为它现在并不清楚。我认为您可能正在寻找jQuery parents()函数。

例如:


<table>
    <tr>
        <td id="content"></td>
    </tr>
</table>

`$("#content").parents("table")` 应该获取 `` 元素。

你对问题的清晰度是正确的,但我得了流感,无法表达得很好。我会去检查一下。谢谢。 - André Alçada Padez


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接