jQuery - 找到选择框的值并打印到正文类
jQuery - Find Val of Select Box and print to body class
我正在尝试编写一个小脚本,将选择框的值打印到body类。
我希望拥有它,以便在值更改时它会自动将旧类交换为新类(值)这是我正在为其处理的脚本的 js 小提琴。
它正在更改类,但在页面加载时找不到选择框的初始值。
任何帮助都会很棒!
http://jsfiddle.net/BMsP8/
jQuery(document).ready(function () {
// On load
jQuery(document).ready(function () {
if (jQuery("select[name=mySelections] option:selected").val() == 'myvalue') {
jQuery("#page_template");
}
});
jQuery('#page_template').change(function () { // on change event
jQuery('body')
//.removeClass() // remove the classes on the body
// or removeClass('class1 class2 ...') in order to not affect others classes
.addClass(jQuery(this).val()); // set the new class
})
我认为问题出在您的selector
尝试一下,
if (jQuery("#page_template").val() == 'myvalue') {
alert(jQuery("#page_template").val());
}
你也可以使用 toggleClass() 代替 addClass() 或 removeClass(),比如,
jQuery('#page_template').change(function () { // on change event
jQuery('body').toggleClass(jQuery(this).val()); // toggle the class
});
演示
设置你的html
<select id="page_template">
<option value="Default">Default</option>
<option value="class1">First Class</option>
<option value="class2">2nd Class</option>
</select>
在 jS 中
$(document).ready(function(){
alert($("#page_template").val());
if ($("#page_template").val() == 'Default') {
$('body').addClass($("#page_template").val());
}
$('#page_template').change(function () { // on change event
$('body').removeClass().addClass($(this).val()); // set the new class
})
});
演示
试试这个:
jQuery('#page_template').change(function () { // on change event
var cls = jQuery(this).val();
jQuery('body').removeAttr("class");
jQuery('body').addClass(cls); // set the new class
});
在这里摆弄。
Hope this helps
**HTML**
<select id="page_template">
<option value="myvalue">Default</option>
<option value="class1">First Class</option>
<option value="class2">2nd Class</option>
</select>
**JS**
jQuery(document).ready(function () {
if (jQuery("#page_template option:selected").val() == 'myvalue') {
jQuery('body').addClass(jQuery("#page_template option:selected").val());
}
jQuery('#page_template').change(function () { // on change event
jQuery('body').removeAttr("class");
jQuery('body').addClass(jQuery(this).val()); // set the new class
});
})
相关文章:
- 使用javascript将动态表从一个html页面打印到另一个html页
- JavaScript打印功能使日历停止工作
- esri javascript异步打印
- 文本框不是从Javascript/Asp.net中的对话框中打印出来的
- jQuery/JavaScript在线公文包表单-打印样式表
- 如何打印嵌套对象的所有值
- 在终端中运行 JavaScript 时(使用 rhino),如何使用 print() 函数在一行中打印
- javascript问题正文样式
- 打印预览没有应用程序页眉和页脚的html表格
- 正在打印图表上的文本
- Rhino打印功能
- JQuery在单击正文时隐藏上下文菜单
- 在通过child.print()打印之前,我如何等待图像加载到我的新窗口中
- 如何用javascript打印php数组
- Javascript,从静态函数中打印全局对象
- 试图打印/调用/或提醒数组中的对象:Getting Undefined
- 打印父节点直到正文
- jQuery - 找到选择框的值并打印到正文类
- Jquery-电子邮件正文-打印编码的URL
- 显示弹出窗口时在模式弹出窗口中打印内容,但如果隐藏模式弹出窗口则打印正文