将 JavaScript 文档转换/更改为 jQuery



对于作业,我需要用纯JavaScript编写我的网站,然后将这些相同的元素转换为jQuery。

我知道jQuery只是JavaScript的一种风格。但是我不明白如何在jQuery中更改我的元素。我以为这就像将我的 html 切换到引导程序,但我看到它不是。

例如,这是我的倒计时时钟的JavaScript代码。我只需要添加一个美元符号而不是 var 吗?请不要将我链接到jQuery教程;由于我已经在看一些了,相反,您能否帮助我了解如何调和两者。

// Set the date we're counting down to
var countDownDate = new Date("June 5, 2018 00:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in an element with id="demo"
document.getElementById("clock").innerHTML = days + "d " +
hours + "h " + minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clock").innerHTML = "EXPIRED";
}
}, 1000);
<div id="clock"></div>

这其实很简单。

使用方法:

document.getElementById("clock").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";    

你只需要使用 jquery 等效,其中 "#clock" 是 jquery 选择器:

$("#clock").html(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");

任何有效的 Javascript 代码在 jQuery 中也是有效的。请记住,jQuery只是Javascript之上的一个库,而不是它的"风格">,它做了很多专门的东西,如DOM操作,AJAX请求等。

jQuery中的$是选择DOM元素的选择器,就像我们在vanilla Javascript中编写document.querySelector()document.getElementById()一样。

典型的jQuery选择器将允许您使用CSS选择器选择DOM元素,如下所示:

$("#YourIDNameHere").click(){
//some event handling logic here
};

首先,使用 CDN 将 jQuery 导入您的应用程序:

<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"> 
</script>
</head>

所以你只需要用jQuery的方式重写下面的代码。

let timeString = `${days} days ${hours} hours ${minutes} minutes ${seconds} seconds`;
$("#clock").html = timeString;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
$("#clock").html = "EXPIRED";
}
}, 1000);

javascript和jQuery中的变量声明将是相同的

当您访问 DOM 的元素时,语法将发生变化

你要么需要从 jquery.org 下载 jQuery--.min.js,要么在 HTML 中链接到它。在这里,我下载了 2.2.0 分钟 js 并在< head >部分的 html 页面中使用

<script type="text/javascript" src="/js/jquery-2.2.0.min.js"></script>

然后在访问元素时,您需要遵循以下语法

获取值

$("#clock").html();

设置值

$("#clock").html("newvalue");

何时使用 .val(( 或 .text(( 或 .html(( 取决于您正在访问的元素

最新更新