I'm creating a series of jQuery checkboxes in a loop like so:
var checkbox = $(' ').attr({type: 'checkbox', id: checkbox_id);
panel.append(checkbox);
panel.append($('').attr({for: checkbox_id}).html(checkbox_name);
checkbox.button();
I have a css class called `my-style` that defines things like `border-radius`, `padding`, and `line-height`. I want `my-style` to override the attributes defined by jQuery's theme for only the checkboxes I've created.
I tried `checkbox.addClass("my-style");` and `panel.find(".ui-button-text").addClass("my-style")`, but neither works correctly. Some css attributes do overwrite jQuery's default values, like `border-radius`, and others don't ever seem to be able to be overwritten like `line-height` and `padding`. I even tried to enforce css attributes directly by `panel.find(".ui-button-text").css("line-height", 1.0);`, but that doesn't work at all.
I understand that I could just modify the jQuery theme directly by changing the css code in there, but doing so would affect all buttons made, which is not what I'd like to do.
UPDATE:
One way I've managed to address this issue is by specifying the `style` tag directly. So the code above becomes:
var checkbox = $(' ').attr({type: 'checkbox',
id: checkbox_id});
panel.append(checkbox);
var label = $('').attr({for: checkbox_id,
style: "font-size: 0.6em; border-radius: 0px; margin-right: 0.3em;"}).text(checkbox_name);
panel.append(label);
checkbox.button();
label.children().attr("style", "padding: 0.2em 0.4em;");
While this solution works, it's unsavory, as I'm mixing JavaScript and CSS code together.
By writing in the `style` attribute, I can override jQuery UI's CSS. One thing that's been discussed here is using more specific CSS selectors that will be given more weight than jQuery UI's CSS classes. A more specific selector would be something that has the checkbox's ID. The problem with this approach is that checkboxes are dynamically generated, and thus so are checkbox IDs. It's therefore not feasible to have more specific CSS selectors from what I understand. 以上就是Modify dynamically created jQuery checkbox button's css的详细内容,更多请关注web前端其它相关文章!
上一篇Why is my jQuery code not able to read an apostrophe? 下一篇JavaScript to make a fast-running image slideshow?