jquery - 从函数调用中获取 html 属性

发布于 2024-09-10 04:23:00 字数 650 浏览 7 评论 0原文

我试图根据锚标记的 id 属性调用不同的工具提示。我的 JavaScript 代码如下:

$(function()
{
   $('.tippy').qtip(
   {
      content: {
          url: "http://mydomain.com/product/mini/" + $(this).attr("id") // doesn't work
      },

      hide: { when: 'mouseout', fixed: true },

       position: {
         corner: {
            target: 'bottomRight',
            tooltip: 'topLeft'
         }
      }
   });

});

我的 html 代码如下所示:

<div>this is the text and I would like to reference the <a href="product.php" class="tippy" id="123456">superproduct</a> with qtip.</div>

我很困难,你能帮我一下吗?

I'm trying to call a different tooltip according to an anchor tag's id attribute. My JavaScript code is as follows:

$(function()
{
   $('.tippy').qtip(
   {
      content: {
          url: "http://mydomain.com/product/mini/" + $(this).attr("id") // doesn't work
      },

      hide: { when: 'mouseout', fixed: true },

       position: {
         corner: {
            target: 'bottomRight',
            tooltip: 'topLeft'
         }
      }
   });

});

my html code looks like this:

<div>this is the text and I would like to reference the <a href="product.php" class="tippy" id="123456">superproduct</a> with qtip.</div>

I'm pretty stuck, could you give me a hand please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羁客 2024-09-17 04:23:00

使用each()

$('.tippy').each(function() {  
   $(this).qtip({
          content: {
              url: "http://mydomain.com/product/mini/" + $(this).attr("id")
          },
          hide: { when: 'mouseout', fixed: true },   
          position: {
             corner: {
                target: 'bottomRight',
                tooltip: 'topLeft'
             }
          }
   });
)};

$(this的原因) 在你的代码中不起作用很简单:它不在函数调用内部(至少不在 this 应该引用 .tippy 的地方) 元素)。 $(this).attr() 在构造传递给 qtip() 的对象时执行。这意味着它与 $('.tippy') 处于相同的上下文中,因此 this 最有可能指的是 window

Use each():

$('.tippy').each(function() {  
   $(this).qtip({
          content: {
              url: "http://mydomain.com/product/mini/" + $(this).attr("id")
          },
          hide: { when: 'mouseout', fixed: true },   
          position: {
             corner: {
                target: 'bottomRight',
                tooltip: 'topLeft'
             }
          }
   });
)};

The reason why $(this) does not work in your code is simple: It is not inside a function call (at least not where this should refer to a .tippy element). $(this).attr() is executed when you construct the object that is passed to qtip(). That means it is in the same context as $('.tippy') and therefore this most probably refers to window.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文