【问题标题】:Dynamically create bootstrap tooltip for fields that are empty为空字段动态创建引导工具提示
【发布时间】:2016-11-24 23:50:28
【问题描述】:

我正在尝试编写 jquery 脚本,让我可以为其中没有值的选择字段创建工具提示。我的要求是它必须在我的 js 代码中动态创建工具提示,这意味着它应该运行而不在 html 代码中编写属性“data-toggle”、“data-placement”和“title”。

问题在于引导工具提示似乎忽略了动态创建的属性。我尝试在 html 代码中手动编写工具提示的属性,它工作正常,但是一旦我将其更改为下面的代码,它就不起作用了。

到目前为止,这是我的代码。如果缩进难以理解,请见谅。

jQuery(function()
{
    jQuery('[id*=form_fields_]').each(function(index, value)
    {
        if (jQuery(this).prop("tagName") == "SELECT" && jQuery(this).val() == "")
        {
            jQuery(this).data('toggle', 'tooltip');
            jQuery(this).data('placement', 'right');
            jQuery(this).attr('title', 'Please select an item');
            jQuery(this).tooltip(
            {
                container: 'body'
            });
            jQuery(this).tooltip();
            jQuery(this).on("hidden.bs.tooltip", function()
            {
                jQuery(this).css("display", "");
                jQuery(this).tooltip('disable');
            });
        }
    });
    jQuery('[data-toggle=tooltip]').tooltip('show');
});

【问题讨论】:

  • 如果添加了工具提示,您是否使用检查元素检查过它?
  • 已检查且未添加任何工具提示。问题是我动态添加了初始化引导工具提示所需的属性。我可以通过删除添加属性的 3 行并将其手动放置在我的 html 代码中来使上述代码工作。
  • 你能添加一个工作小提琴吗?并从 Ikkun 看到下面的答案。我认为这可以解决您的问题。

标签: javascript jquery html twitter-bootstrap


【解决方案1】:
jQuery(function()
{
    jQuery('[id*=form_fields_]').each(function()
    {
        if (jQuery(this).val().length <=0)
        {
            jQuery(this).data('toggle', 'tooltip');
            jQuery(this).data('placement', 'bottom');
            jQuery(this).attr('title', 'Please select an item');
            jQuery(this).tooltip(
            {
                container: 'body'
            });
        }
        jQuery(this).keyup(function()
        {
                console.log(jQuery(this).val().length);
            if (jQuery(this).val().length <=0)
            {
                jQuery(this).data('toggle', 'tooltip');
                jQuery(this).data('placement', 'bottom');
                jQuery(this).attr('title', 'Please select an item');
                jQuery(this).tooltip(
                {
                    container: 'body'
                });
                if(jQuery(this).focus()){
                    jQuery(this).tooltip(
                    {
                        container: 'body'
                    });
                }
            }
            else
            {
                jQuery(this).tooltip('destroy');     
            }
        });
    });
});

jsfiddle https://jsfiddle.net/qekg2zpm/12/

【讨论】:

  • 当为空时它返回 0。这么多工作,或者你的意思是别的什么?
猜你喜欢
  • 2021-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多