[英]jQuery attr() method to change a class name
当从下拉菜单中选择一个选项时,我试图使用attr()jQuery方法更改h1元素的类名称。 我希望更改类名以访问不同的CSS属性(字体)
我认为我没有深入研究DOM来改变类吗?
function myFontStyle() { $('#font').on("change", function() { var fontChange = this.value console.log(this.value); $('h1').attr('class', + fontChange); }); } myFontStyle();
.handwriting{ font-family: 'Pacifico', cursive; } .sketch{ font-family: 'Fredericka the Great', cursive; } .print{ font-family: 'Sigmar One', cursive; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="font">Choose font</label> <select name="font" id="font"> <option value="handwriting">Handwriting</option> <option value="sketch">Sketch</option> <option value="print">Print</option> </select> <div class="card celadonBackground"> <div id="coverImage"> <img src="assets/birthday.jpg"/> </div> <div class="noBorder"> <h1 class="sketch">Happy birthday to you</h1> </div> </div>
您可以根据您的jQuery版本使用attr或prop:
$(selector).attr('class', 'className'); // jQuery < 1.6
$(selector).prop('class', 'className'); // jQuery >= 1.6
向现有班级添加班级
var classes = $(selector).prop('class');
$(selector).prop('class', classes + ' className');
删除课程
var classes = $(selector).prop('class').replace('notNeededClass', '');
$(selector).prop('class', classes);
但是jQuery直接提供了classManipulation
$(selector).addClass('className');
$(selector).removeClass('className');
$(selector).toggleClass('className');
主要地, .attr()
方法不适用于类操作。 采用:
$(selector).addClass('className') for adding class to element(s)
$(selector).removeClass('className') for removing class from element(s)
$(selector).toggleClass('className') for toggling class appereance in element(s)
更改$('h1').attr('class', +fontChange);
至
$('h1').attr('class', fontChange);
function myFontStyle() { $('#font').on("change", function() { var fontChange = this.value //console.log(this.value); $('h1').attr('class', fontChange); console.log('h1 has now class: ', $('h1').attr('class')) }); } myFontStyle();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="font">Choose font</label> <select name="font" id="font"> <option value="handwriting">Handwriting</option> <option value="sketch">Sketch</option> <option value="print">Print</option> </select> <div class="card celadonBackground"> <div id="coverImage"> <img src="assets/birthday.jpg"/> </div> <div class="noBorder"> <h1 class="sketch">Happy birthday to you</h1> </div> </div>
语法错误
function myFontStyle() {
$('#font').on("change", function() {
var fontChange = this.value
console.log(this.value);
$('h1').attr('class', fontChange);
});
}
myFontStyle();
$("h1").attr('class', fontChange);
要么
$("h1").addClass(fontChange);
您可以查看详细信息表格
http://api.jquery.com/category/manipulation/class-attribute/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.