简体   繁体   English

使用jQuery修改CSS类的名称-负载不起作用

[英]Using jQuery to modify the name of a CSS class - Not working on load

I have the following code (using XSLT/HTML) 我有以下代码(使用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. “ ClassName”通过CMS动态运行,当选择了两个选项时,它们由其他字符分隔。 As a result you end up with something similar to this: 结果,您得到的结果与此类似:

;#class1;#class2;#

What I'm trying to do is modify the class names based on what they are currently set to. 我想做的是根据当前设置的类名称来对其进行修改。 I written the following code, which when entered into the browsers console window, works an absolute charm. 我编写了以下代码,当将它们输入到浏览器控制台窗口中时,它绝对具有魅力。 However, when added to the actual page, it doesn't take effect. 但是,当添加到实际页面时,它不会生效。 I'm wondering if it's a priority thing or something else: 我想知道这是优先事项还是其他事项:

$('.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 );}    
});

Any help on this would be greatly appreciated. 任何帮助,将不胜感激。

Thanks in advance :) 提前致谢 :)

In order to trigger a function on page load, you need to wrap it in a DOM ready. 为了在页面加载时触发功能,您需要将其包装在DOM中。

Here is a tutorial on DOM ready for jquery . 这是有关可用于jquery的DOM的教程。

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

The class names in your html contain special characters that is the reason why jquery didn't find the selector. html中的类名称包含特殊字符,这就是jquery找不到选择器的原因。 Source jquery site. jQuery站点。

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar") 要将任何元字符(例如!“#$%&'()* +,。/ :; <=>?@ [] ^`{|}〜)用作名称的文字部分,必须用两个反斜杠转义:\\。例​​如,一个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 FIDDLE示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM