.find()-结果的根

Root of .find()-result

我有这样一个DOM

<html>
  you clicked <span>0</span> times

  <div class="button" countSelect=">span">
    you clicked <span>0</span> times.
  </div>
</html>

这是我的 javascript:

function increase(i,e){
  var $e = jQuery(e);
  $e.text($e.text() * 1 + 1);
}
function handle(){
  var selectText = $(this).attr('countSelect');
  $(this).find(selectText).each(increase);
}
$(function(){
  $('.button').click(handle);
});

我需要什么作为 countSelect-Attribute-value to select 第一个跨度而不改变 javascript?

我之前做过什么?

  1. 我尝试使用 *:root > span
  2. 我尝试使用 *:parent:parent > span

两者都解析为 0 的长度。

FIDDLE

顺便说一句:我可以拥有额外的插件或额外的库。

这与我遇到的另一个问题有关,希望对您有所帮助。只要您可以更改 jQuery 代码中的一行,您就可以支持向上和向下 DOM 选择器。虽然可以用此代码替换 find,但不推荐(甚至一点也不):)

我创建了一个名为 findThis 的小型 jQuery 扩展方法,它允许您使用 :this 伪选择器。在 运行 时,它将临时 ID 放在 "current" 元素上,并在选择器中用该 ID 替换 :this。然后它将选择器应用于 document。这允许像“div:has(:this)”这样的酷选择器有效地允许您在 DOM.

上下搜索

JSFiddle: http://jsfiddle.net/TrueBlueAussie/08zm3vLu/2/

您需要将 HTML 更改为:

<button class="button" countSelect=":this > span">you clicked <span>0</span> times.</button>
<button class="button" countSelect="span:first()">you clicked <span>0</span> times.</button>
<button class="button" countSelect="span:first()">you clicked <span>0</span> times.</button>

还有一行代码:

$(this).findThis(selectText).each(increase);

这在不改变现有 HTML 或 JavaScript 的情况下工作:

    function increase(i,e){
      var $e = jQuery(e);
      $e.text($e.text() * 1 + 1);
    }
    function handle(){
      var selectText = $(this).attr('countSelect');
      var $k = $(this).find(selectText);
      console.debug($k);
        $k.each(increase);
    }

    $(function(){
      $('.button').click(handle);
    });
    if (!jQuery.fn.findOrig){
      jQuery.fn.findOrig = jQuery.fn.find;
      jQuery.fn.find = function(selector){
        if (selector[0]==='p' && selector.indexOf('parent') === 0) {
            return this.parent().find(selector.slice(6));
        }
        if (selector[0]===':' && selector.indexOf(':root') === 0) {
            return jQuery(document.body).findOrig(selector.slice(5));
        }
        return this.findOrig(selector);
      }
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


you clicked <span>0</span> times
      
<button class="button" countSelect=">span">
  you clicked <span>0</span> times.
</button>

<button class="button" countSelect=":root > span">
  you clicked <span>0</span> times.
</button>