Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

javascript - Add CSS rule via jQuery for future created elements

I have a somewhat unusual issue. I've done something like this many times:

$('#selector').css('color','#00f');

My problem is that I create a <div id="selector">, and I call the command above and it works fine.

Now, on another event, later, I remove that element from the DOM and add it again at a later time with the same id. This element now doesn't have color:#00f.

Is there a way that I can add a rule in CSS, such that it will affect items that are created in the future with that same id/class? I like jQuery, but anything with plain JavaScript would be fine as well.

It has to be dynamic, and I don't know the classes to put in a CSS file. Also, I plan on changing a single attribute a few different times through the course of the application. For example, setting the color to black, to blue, to red, and back to black.



I went with the answer from @lucassp, and this is what I ended up with:

function toggleIcon(elem, classname)
{
    if($(elem).attr('src')=='img/checkbox_checked.gif')
    {
        $(elem).attr('src', 'img/checkbox_unchecked.gif')
        //$('.'+classname).hide();//this was the old line that I removed
        $('html > head').append($('<style>.'+classname+' { display:none; }</style>'));
    }
    else
    {
        $(elem).attr('src', 'img/checkbox_checked.gif')
        //$('.'+classname).show();//this was the old line that I removed
        $('html > head').append($('<style>.'+classname+' { display:block; }</style>'));
    }
}

I also want to say that @Nelson is probably the most "correct", though it would require more work to go into application code that always works fine, and that's not effort I want to spend at the moment.

If I had to rewrite this (or write something similar) in the future, I would look into detach().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should work:

var style = $('<style>.class { background-color: blue; }</style>');
$('html > head').append(style);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...