在单独的元素中更改javascript变量

时间:2015-04-16 14:54:05

标签: javascript html class variables element

我运行基于php(phpbb),javascript和html的WoW公会论坛。从那以后,Wowhead允许将链接发布到他们的项目/拼写ID等.Wowhead JS的基本代码及其变量是:

<script src="//static.wowhead.com/widgets/power.js"></script>
<script>var wowhead_tooltips = { "colorlinks": true, "iconizelinks": true, "renamelinks": true }</script>

有一个扩展程序可以通过HTML文件将此代码放在每个页面的页脚中。发布的每个Wowhead链接都将在链接中转换,并提供工具提示,说明其链接的内容。 wowhead_tooltips变量的'“renamelink”:true'部分使得项目或法术的任何链接都重命名为链接的确切名称。

问题:当我使用Wowhead链接生成自定义URL时,即:

<a href="http://www.wowhead.com/spell=1953">Teleport</a>

不是使用Blink的工具提示显示“Teleport”,而是使用图标将整个URL重命名为Blink,如wowhead_tooltips变量中所述。

我想要实现的目标是:

  1. 任何指向Wowhead的直接网址都应转换为重命名的拼写/项目。
  2. 任何指向Wowhead的自定义网址都应保留其自定义文字,但请检索工具提示。
  3. 这应该可以在一个页面上完成。
  4. 我提出的最佳解决方案是根据类向var wowhead_tooltips添加一个'if'函数,然后将该类添加到URL:

    <script>if ($('a').hasClass("wowrename")) { var wowhead_tooltips = { "colorlinks": true, "iconizelinks": true, "renamelinks": false } }</script>
    <a class="wowrename" href="http://www.wowhead.com/spell=1953">Teleport</a>
    

    但是,这个解决方案的问题在于,一旦脚本在页面上识别出一个带有“wowrename”类的URL,它就会停止重命名所有链接,这意味着自定义URL和直接URL不能混合在一起一页。

    我尝试过的任何其他解决方案,使用ID,定义不同的变量等都不起作用或提出相同的限制。

    因此,问题是,是否可以根据id,class或其他任何内容更改Javascript变量(在本例中为“var wowhead_tooltips {”renamelinks“:false}”每个元素(URL)?

3 个答案:

答案 0 :(得分:0)

你必须循环所有链接,如下所示:

$("a.wowrename").each(function() {
    // some code
});

答案 1 :(得分:0)

这是一个简单的解决方案。这不是最好的方式。

var wowhead_tooltips = { "colorlinks": true, "iconizelinks": true, "renamelinks": true }
$('a').hover(function() {
  if ($(this).hasClass('wowrename') {
    wowhead_tooltips.renamelinks = true;
  }
  else {
    wowhead_tooltips.renamelinks = false;
  }
});

我不知道wowhead API究竟是如何工作的,但是如果wowhead_tooltips变量在用户使用鼠标指向链接的时刻(没有任何超时)正好加载 - 这可能会失败或随机工作/不工作。
原因可能是javascript不知道首先执行哪个函数。

我希望这会奏效。如果不是 - 评论我会以另一种方式思考。

答案 2 :(得分:0)

使用工具提示和iccn重命名的直接链接。

<a href="http://www.wowhead.com/spell=1953">Teleport</a>

带工具提示和原始文字的自定义链接。 我已将原始链接文本存储为数据属性,因此我们可以在更改后将其恢复。

<a class="wowrename" href="http://www.wowhead.com/spell=1953" data-value="Teleport">Teleport</a>

继续检查static.wowhead.com/widgets/power.js何时更改上一个链接文字。更改后,使用data-value值进行恢复,删除添加的样式,创建图标并停止计时器。

$(function () {
    //timmer
    checkChanged = setInterval(function () {
        // check for when the last link text has changed
        var lastItem = $("a.wowrenameoff").last();
        if (lastItem.text() !== lastItem.data('value')) {
            $("a.wowrenameoff").each(function () {
                //change value
                $(this).text($(this).data('value'));
                //remove icon
                $(this).attr('style', '');

                //stop timer
                clearInterval(checkChanged);
            });
        }

        i++;
    }, 100);
});

这会导致链接图标闪烁然后关闭,但在页面刷新后会重复。

JSFiddle demo