Ответ 1
Заменить:
$("#spanText").attr("css", { backgroundColor: "gray" });
с
$("#spanText").attr('style', 'background-color:gray');
Я читаю книгу "Справочник по jQuery Pocket", OReilly, 2011 На странице 15 сказано
'Например, вызов attr ("css", {backgroundColor: "grey"}) аналогичен вызову css ({backgroundColor: "grey"}). "
Но я не могу заставить attr ('css', {}) работать. Мой тестовый код: http://jsfiddle.net/4UMN3/4/
$(function() {
$("#btnChangeColor").click(function () {
$("#spanText").attr("css", { backgroundColor: "gray" });
});
});
метод css() работает нормально, http://jsfiddle.net/4UMN3/5/
Заменить:
$("#spanText").attr("css", { backgroundColor: "gray" });
с
$("#spanText").attr('style', 'background-color:gray');
Возможно, он должен был быть
$("#spanText").attr('style', 'background-color:gray');
Это может работать, но имеет некоторые проблемы:
style
вместо атрибута style
.Затем, если вы используете jQuery, лучше используйте метод css
:
$("#spanText").css('background-color', 'gray');
Но свойство style
полезно в vanilla-js:
document.getElementById("spanText").style.backgroundColor = 'gray';
Я думаю, что jQuery.attr() может влиять только на атрибуты, которые имеет элемент.
HTMLElements не знают атрибута css (значение <div css="something"></div>
).
Итак, правильное использование было бы
$("#spanText").attr("style",{backgroundColor:"gray"});
Но это выводит
<span id="spanText" style="[object Object]">This is a test</span>
Пример, который действительно работает, -
$("#spanText").attr("style","background-color:gray;");
$("#id").attr('style', 'color:red;cursor:pointer');
= > .css-метод изменяет атрибут style, а не "css".
$().att('style' , 'backgroundColor : gray');
= > нет такой вещи, как css-атрибут в html
вы используете jQuery, поэтому вы должны использовать css, а не attr, потому что css добавьте свойство, но attr заменит весь стиль, если будет!
<style>
.newClass{
color:#fff;
}
.test2{
color:red;
}
.newclass{
color:blue;
}
</style>
<script>
$(document).ready(function(){
//get style and class name in alert
$('#attr').click(function () {
alert($('h3').attr("style"));
alert($('h3').attr("class"));
});
//set css property
$("#setcss").click(function(){
$("#test").css({"background-color": "#000", "color": "teal"});
});
//change class name property
$('#changeclassname').click(function(){
$('#test3').removeClass('test2').addClass('newclass');
});
});
</script>
<!--get style and class name in alert-->
<h3 class="test" style="color: white; background: red;">This is the tag and this will be our tag</h3>
<button id="attr">get Attribute</button>
<!--set css property-->
<p id="test" class="test1">This is some <b>bold</b> text in a paragraph.</p>
<button id="setcss">set Attribute</button>
<!--change class name property-->
<p id="test3" class="test2">This is some text in a paragraph.</p>
<button id="changeclassname">set Attribute</button>