Javascript href 属性用于 css 未更新

Javascript href attribute for css not updating

本文关键字:更新 css 用于 href 属性 Javascript      更新时间:2023-10-22

我正在学习jquery,为了测试我的技能,我创建了一个可以使用jquery切换样式的按钮,但由于某种原因,该按钮不起作用。 有什么想法吗?法典:

<link id="original" rel="stylesheet" type="text/css" href="http://style.es.cx/style2.css">
<script>
function turnGrey(){
    document.getElementById("original").href="http://style.es.cx/style.css";<!-- what ever your new css file is called-->
}
</script>
<button id="grey" onclick="turnGrey">Turn Grey</button><br />
<pre>this text should change</pre>
<div>
    foobar
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

你必须用()调用函数:

 onclick="turnGrey()"

<!-- what ever your new css file is called-->这不是在<script>发表评论的方式.

你有很多错误。

  1. 你使用的是vanilla javascript,而不是jQuery(你包括库,但使用的语法不是jQuery(。

  2. 您的函数不起作用,因为您没有调用它。您需要onclick="turnGrey()"时,您正在编写onclick="turnGrey".

  3. 更改样式表不是好的做法。最好更改类名。

  4. javascript中的注释是这样的:/* comment */。您正在JavaScript代码中用HTML编写注释,这会完全崩溃您的代码。

但是,这里是可以工作的代码(我删除了jQuery库,因为您没有使用不要吃机器资源(:


<link id="original" rel="stylesheet" type="text/css" href="http://style.es.cx/style2.css">
<script>
function turnGrey(){
    document.getElementById("original").href="http://style.es.cx/style.css"; /* what ever your new css file is called */
}
</script>
<button id="grey" onclick="turnGrey()">Turn Grey</button><br />
<pre>this text should change</pre>
<div>
foobar
</div>

这里的问题是turnGrey()是一个函数,但在你的onclick中你只有函数名称。 您实际上并没有调用该函数。 将onclick="turnGrey"更改为onclick="turnGrey()",它应该可以工作。

你在做什么?顺便说一下,这是更改 css 的一种方法。或者您也可以添加或删除类

$("#grey").removeClass("success").addClass("danger");

<link id="original" rel="stylesheet" type="text/css" href="http://style.es.cx/style2.css">
<script>
function turnGrey(){
    $("#grey").css('color', 'red');
    $("#grey").css('background-color', 'green');
}
</script>
<button id="grey" onclick="turnGrey()">Turn Grey</button><br />
<pre>this text should change</pre>
<div>
foobar
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>