使用 jQuery 更改工具提示标题

Changing tooltip title using jQuery

本文关键字:工具提示 标题 jQuery 使用      更新时间:2023-09-26

帮帮我,因为我是jQuery和Web开发的新手。我的要求是省略(...)文本框中的长文本然后,如果鼠标悬停在它们上面,则在工具提示中显示全文。

为此,我使用了Bootstrap的工具提示。我所做的是以下几点:

下载了引导 js 并包含在我的文件中,如下所示:

 <script type="text/javascript" src="scripts/bootstrap.min.js"></script>        

像这样改变了我的肚子

<input type="text" name="tooltip" id="samplebox" data-toggle="tooltip" title="Ankit" >

对于动态更新标题,我使用了jQuery

<script>
    $(document).ready(function(){
        $(" #samplebox ").mouseenter(function(){
            var word = document.getElementById("samplebox").value;
            $(" #samplebox ").attr('title', word);
        });     
    });
</script>

这对于一个元素来说效果很好。

现在我必须对更多的文本框做同样的事情,它们的数量可以不断增加。现在,我想创建一个通用函数,我可以在其中传递id并完成鼠标悬停在上面的任何文本框。

如果没有样式类,请使用属性选择器。对于工具提示,还有属性值 data-toggle="tooltip"

$(document).ready(function(){
    $("[data-toggle=tooltip]").mouseenter(function () {
        var $this = $(this);
        $this.attr('title', $this.val());
    });   
});

演示

注意:要与 Bootstrap 的工具提示一起使用,您可能需要更改属性data-original-title,如果title更新工具提示的内容。看看这个问题

上面的代码都不适用于我的引导工具提示。但是,更改data-original-title解决了该问题:

document.getElementById("samplebox").setAttribute("data-original-title", "newText");
你可以

像这样使用类选择器

<input type="text" name="tooltip" class="samplebox" data-toggle="tooltip" title="Ankit" >
    <script>
    $(document).ready(function(){
        $(".samplebox").mouseenter(function(){
            var word = $(this).value();
            $(this).attr('title', word);
        });     
    });
</script>

这将在不需要创建任何泛型函数的所有文本框上触发事件

$(":input").mouseenter(function(){
   var val = $(this).val();
   $(this).attr('title', val);
});

首先将公共类添加到每个文本框。

<input type="text" name="tooltip" class="myclass" data-toggle="tooltip" title="Ankit" >

那么jQuery看起来像这样。

  <script>
    $(document).ready(function(){
        $(".myclass").mouseenter(function(){
            var word = document.getElementById("samplebox").value;
            $(this).attr('title', word);
        });     
    });
  </script>