如何通过Jquery获得直接的父母?

时间:2015-07-13 10:10:50

标签: jquery html

html:

<span class="ui-spinner ui-widget ui-widget-content ui-corner-all"><input class="spinner1 ui-spinner-input" id="q1" name="value" value="1" min="1" aria-valuemin="1" aria-valuenow="2" autocomplete="off" role="spinbutton"><a class="ui-spinner-button ui-spinner-up ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only" tabindex="-1" role="button" aria-disabled="false"><span class="ui-button-text"><span class="ui-icon ui-icon-triangle-1-n">▲</span></span></a><a class="ui-spinner-button ui-spinner-down ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only" tabindex="-1" role="button" aria-disabled="false"><span class="ui-button-text"><span class="ui-icon ui-icon-triangle-1-s">▼</span></span></a></span>

jquery的:

$('.ui-spinner-button').click(function() {
    //
});

我想获得aria-valuenow的id和值

<input class="spinner1 ui-spinner-input" id="q1" name="value" value="1" min="1" aria-valuemin="1" aria-valuenow="2" autocomplete="off" role="spinbutton">

点击.ui-spinner-button

我该怎么做?我用Google搜索了几天但没有运气。

3 个答案:

答案 0 :(得分:2)

此处您不需要parent,您需要prev兄弟。要获取上一个输入,请使用siblings()选择器。

请参阅以下代码中的评论:

$('.ui-spinner-button').click(function() {

  // Get the spinner input jquery object
  var $input = $(this).siblings('.ui-spinner-input');


  // Get attribute values
  var id = $input.attr('id'),
    valueNow = $input.attr('aria-valuenow');
  alert(id + ' >>> ' + valueNow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<span class="ui-spinner ui-widget ui-widget-content ui-corner-all">
  <input class="spinner1 ui-spinner-input" id="q1" name="value" value="1" min="1" aria-valuemin="1" aria-valuenow="2" autocomplete="off" role="spinbutton">
<a class="ui-spinner-button ui-spinner-up ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only" tabindex="-1" role="button" aria-disabled="false"><span class="ui-button-text"><span class="ui-icon ui-icon-triangle-1-n">▲</span></span>
</a><a class="ui-spinner-button ui-spinner-down ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only" tabindex="-1" role="button" aria-disabled="false"><span class="ui-button-text"><span class="ui-icon ui-icon-triangle-1-s">▼</span></span></a>
</span>

答案 1 :(得分:1)

我不确定您为什么需要parentNode$.parent()。使用$(element).parent()获取直接父级。在你的情况下:

$('.ui-spinner-button').click(function(){
  $(this).parent(); // gives you the immediate parent as a jQuery object.
  $(this).attr("aria-valuenow"); // gives aria-valuenow.
  $(this).attr("id"); // gives you the ID
  this.id; // gives you the ID
});

答案 2 :(得分:1)

这是适用于我的JQuery代码:

$('.ui-spinner-button').click(function () {
    var elem = $(this).parent().find("input");
    alert("id: "+ elem.attr("id")+ ", aria-valuenow: "+ elem.attr("aria-valuenow")));
});

Here is a JSFiddle demo