如何仅针对某些元素触发jQuery函数

时间:2017-05-17 17:38:20

标签: javascript jquery

我已经尝试了所有我能找到的解决方案,但没有运气。

此代码目前用于从标题属性创建工具提示。我试图让它仅在元素具有特定类.tooltipit时运行,而不是在具有标题属性的所有元素上运行。

你可以看到我试图在类选择器中发出这个函数的位置(在结尾处注释掉),我希望它可以工作,但是没有。

jQuery(document).ready( function($) {

    // textFrom : String, the attribute from which the text
    //            should come,
    // delta :    String or Number, the distance from the cursor at
    //            which the tooltip should appear
    function instantTooltips(textFrom, delta) {
        // if delta exists, and can be parsed to a number, we use it,
        // otherwise we use the default of 5:
        delta = parseFloat(delta) ? parseFloat(delta) : 5;

        // function to handle repositioning of the created tooltip:
        function reposition(e) {
            // get the tooltip element:
            var tooltip = this.nextSibling;
            // setting the position according to the position of the
            // pointer:
            // tooltip.style.top = (e.pageY + delta) + 'px';
            // tooltip.style.left = (e.pageX + delta) + 'px';
            // tooltip.style.top = (e.pageY + delta - 190) + 'px';
            // tooltip.style.left = (e.pageX + delta - 200) + 'px';
        }

        // get all elements that have an attribute from which we
        // want to get the tooltip text from:
        var toTitle = document.querySelectorAll('[' + textFrom + ']'),
        //create a span element:
        span = document.createElement('span'),
        // find if we should use textContent or innerText (IE):
        textProp = 'textContent' in document ? 'textContent' : 'innerText',
        // caching variables for use in the upcoming forEach:
        parent, spanClone;
        // adding a class-name (for CSS styling):
        span.classList.add('createdTooltip');
        // iterating over each of the elements with a title attribute:
        [].forEach.call(toTitle, function(elem) {
            // reference to the element's parentNode:
            parent = elem.parentNode;
            // cloning the span, to avoid creating multiple elements:
            spanClone = span.cloneNode();
            // setting the text of the cloned span to the text
            // of the attribute from which the text should be taken:
            spanClone[textProp] = elem.getAttribute(textFrom);

            // inserting the created/cloned span into the
            // document, after the element:
            parent.insertBefore(spanClone, elem.nextSibling);

            // binding the reposition function to the mousemove
            // event:
            elem.addEventListener('mousemove', reposition);

            // we're setting textFrom attribute to an empty string
            // so that the CSS will still apply, but which
            // shouldl still not be shown by the browser:
            elem.setAttribute(textFrom, '');
        });
    }

    // $('.tooltipit').each(function() {
    //  instantTooltips('title', 15);
    // });

    // calling the function:
    instantTooltips('title', 15);

});

3 个答案:

答案 0 :(得分:0)

目前您的querySelector是[title](所有具有title属性的元素)。如果您按照要求提供类名,它应该可以工作,例如:

var toTitle = document.querySelectorAll('.tooltipit[' + textFrom + ']');

只会选择带有class =' tooltipit'的页面元素。并具有标题属性。

答案 1 :(得分:-1)

将其重写为正确的jQuery插件,一切都更容易



jQuery(document).ready(function($) {
  jQuery.fn.instantTooltips = function(delta) {
    delta = parseFloat(delta) || 5;

    return this.each(function() {
      var span = $('<span />', {
        text: $(this).attr('title'),
        css: {
          position: 'absolute',
          top: 0,
          left: 0,
          display: 'none'
        },
        'class': 'createdTooltip'
      });

      $(this).on({
        mousemove: function(e) {
          $(this).prev().css({
            top: e.pageY + delta,
            left: e.pageX + delta
          });
        },
        mouseenter: function() {
          $(this).prev().show();
        },
        mouseleave: function() {
          $(this).prev().hide();
        }
      }).before(span);
    });
  }

  $('.tooltip').instantTooltips(15)

});
&#13;
.createdTooltip {
  background: red;
  color: white;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tooltip" title="show this">Mouse here for tooltip !</div>
<br />
<br />
<div class="nope" title="show this">This does not have the class !</div>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

您是否尝试过以下内容?

$('.tooltipit').each(function() {
  $(this).on('mouseenter', function(){
    instantTooltips('title', 15);
  }
});