質問

I have the following code (using 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. 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.

Here is a tutorial on DOM ready for jquery.

$(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. Source jquery site.

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")

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top