【问题标题】:Using jQuery to modify the name of a CSS class - Not working on load使用 jQuery 修改 CSS 类的名称 - 无法加载
【发布时间】:2013-07-16 00:22:43
【问题描述】:

我有以下代码(使用 XSLT/HTML)

<div class="{@ClassName} modify""><img src="{substring-before(@Image, ', ')}"/></div>

The "ClassName" is being through dynamically through a CMS, which when there are two options selected, they are segregated by a bunch of other characters.结果你会得到类似这样的结果:

;#class1;#class2;#

我要做的是根据当前设置的类名修改类名。我编写了以下代码,当输入到浏览器控制台窗口时,它具有绝对的魅力。但是,当添加到实际页面时,它不会生效。我想知道这是优先事项还是其他:

$('.modify').each(function(){
var newPrimeItem= "primary item";
var newItem = "item";
if ( $(this).attr('class') == ";#primary;#item;# modify") { $(this).attr('class', newPrimeItem);}
if ( $(this).attr('class') == ";#item;# modify") { $(this).attr('class', newItem );}    
});

对此的任何帮助将不胜感激。

提前致谢:)

【问题讨论】:

  • 该代码是否准备好包装在 DOM 中或放在文档末尾?
  • 你有一个名为“;#primary;#item;# modify”的类吗?
  • 你的类名很乱。你可以在这里查看规则api.jquery.com/category/selectors
  • 文档中已经准备好了。 Bob,正如我所说,这是从内容管理系统生成的,因此我尝试修改它并使其更清洁。塞尔吉奥,是的,我愿意 :)

标签: javascript jquery css classname


【解决方案1】:

您的 html 中的类名包含特殊字符,这就是 jquery 找不到选择器的原因。来源jquery 网站。

使用任何元字符(例如 !"#$%&'()*+,./:;?@[]^`{|}~ )作为文字名称的一部分,它必须 用两个反斜杠转义:\。例如,一个元素 id="foo.bar",可以使用选择器$("#foo\.bar")

$('.modify').each(function(){
    var newPrimeItem= "primary item";
    var newItem = "item";

    var me = $(this);
    //remember that classes are separated with space
    if (me.hasClass("\\;\\#primary\\;\\#item\\;\\#") && me.hasClass("modify"))
    { 
        me.attr('class', newPrimeItem);
    }
    if ( me.hasClass("\\;\\#item\\;\\#")  && me.hasClass("modify") ) 
    { 
        me.attr('class', newItem );
    }    
});

FIDDLE example

【讨论】:

  • 谢谢鲍勃 - 感谢。代码开始工作。不幸的是,同事将其从准备好的文档中剥离出来而不调用该函数是一个可怕的错误。否则它工作正常。谢谢你的时间:)
  • 协作作品经常出现这种情况。很高兴它现在起作用了。
【解决方案2】:

为了在页面加载时触发函数,您需要将其包装在准备好的 DOM 中。

这是DOM ready for jquery的教程。

$(document).ready(function() {
    // Code to be executed on page load.
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-12
    • 2017-06-13
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    相关资源
    最近更新 更多