【问题标题】:jQuery maphilight set area to alwaysOn by clickjQuery maphilight 通过单击将区域设置为 alwaysOn
【发布时间】:2015-01-05 09:24:56
【问题描述】:

我正在使用 David Lynch 的 jQuery maphilight (http://davidlynch.org/projects/maphilight/docs/) 来突出显示图像上的图像映射区域。特别是,此演示 (http://davidlynch.org/projects/maphilight/docs/demo_features.html) 展示了如何设置 data-maphilight="{'alwaysOn:true'}" 以使给定的地图区域“始终开启”。

我想根据点击的项目设置“始终开启”。所以我尝试了这个:

$(this).attr('data-maphilight', '{\'alwaysOn\':true}');

使用 Firebug,我可以看到该属性在被点击时被添加到我的元素中,例如:

<area data-county="Susquehanna" href="#" coords="589,62,590,117,518,118,511,62" shape="poly" data-maphilight="{'alwaysOn':true}">

但是,该元素没有保持突出显示。

如果我手动(在 HTML 标记中)设置 alwaysOn,像这样:

<area shape="poly" coords="447,193,442,225,453,222,467,226,467,235,472,235,475,242,486,242,489,251,448,268,420,276,433,257,434,246,438,235,428,220,433,206,430,194,438,191" href="#" data-county="Northumberland" data-maphilight='{"alwaysOn":true}'>

...它确实有效。这是单引号和双引号的混合吗?当我使用 jQuery "attr" 语句时,它会自动使用双引号,所以我不得不反转它们。或者,这是一个仅设置该属性不会导致 jQuery 插件更新的问题吗?

如果我尝试修改此脚本以执行我想要的操作,我将不胜感激。

谢谢!

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    这是单引号和双引号的混合吗?

    当你设置数据属性时。 jQuery 尝试将字符串解析为 JSON,但前提是它是有效的 JSON。因此,data-maphilight='{"alwaysOn":true}' 包含一个有效的 JSON,而 data-maphilight="{'alwaysOn':true}"。请注意用于分隔字符串的单引号会产生错误的 JSON。

    这是一个仅设置该属性不会导致 jQuery 插件更新的问题吗?

    嗯,设置数据属性和设置数据对象是不同的。

    // Changes the data-maphilight attribute to the string '{\'alwaysOn\':true}'
    $(this).attr('data-maphilight', '{\'alwaysOn\':true}');
    // Sets the internal data object to {'alwaysOn': true}. This is a javascript object, not JSON.
    $(this).data('maphilight', {'alwaysOn': true});
    

    所以一旦创建了对象,如果你想修改它,你需要使用.data而不是.attr

    更改属性而不导致更新的问题可能是因为我们需要一种方法来通知插件发生了更改。我在您提到的示例代码中看到此插件使用.trigger('alwaysOn.maphilight') 来触发此通知。那么,完整的变更声明应该是这样的:

    $(this).data('maphilight', {'alwaysOn': true}).trigger('alwaysOn.maphilight');
    

    请注意,执行此分配会将当前的 maphilight 数据对象替换为 {'alwaysOn': true} 替换之前的数据对象。

    【讨论】:

    • 谢谢你,非常有帮助,这很有效。我对 attr 与 data 有了更好的理解。不过,我仍然对 trigger('alwaysOn.maphilight') 的作用有些困惑。或者为什么除了“数据”部分之外还需要它。
    猜你喜欢
    • 2012-03-21
    • 2014-04-18
    • 1970-01-01
    • 2013-03-26
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多