更改工具提示文本jquery

时间:2018-03-08 23:47:08

标签: javascript jquery html

假设title属性用作工具提示的文本。是否可以使用jQuery更改文本?

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h3>Tooltip Example</h3>
  <a href="#" id="tool" data-toggle="tooltip" title="Hfdfd!">Hover over me</a>
</div>

<script>
$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();   
});
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

我无法通过选项更改它,因为我相信api说使用标题是告诉它如果标题不在那里应该是什么值。我通过将标题更改为data-title并将标题选项作为返回此值的函数来实现它。

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip({
      title: function () {
        return this.getAttribute('data-title');
      }
    });
    
    setInterval(function(){
      $('[data-toggle="tooltip"]').attr('data-title', Date.now());
    }, 1000);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
  <h3>Tooltip Example</h3>
  <a href="#" id="tool" data-toggle="tooltip" data-title="Hfdfd!">Hover over me</a>
</div>