如何将jQuery添加到HTML页面

如何将jQuery添加到HTML页面

本文介绍了如何将jQuery添加到HTML页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这段代码来放置在html页面中,但是我对javascript一无所知,所以我不知道将其放置在何处以及将其放置在哪种标签中.

I was given this chunk of code to place in my html page but I know nothing about javascript so I have no idea where to place it and what kind of tag to place it in.

$('input[type=radio]').change(function() {

$('input[type=radio]').each(function(index) {
  $(this).closest('tr').removeClass('selected');
});

$(this).closest('tr').addClass('selected');
});

推荐答案

包括jQuery库

那是jQuery代码.您首先需要确保jQuery库已加载.如果您自己没有托管库文件,则可以从 jQuery CDN 进行热链接:

That is jQuery code. You'll first need to make sure the jQuery library is loaded. If you don't host the library file yourself, you can hotlink one from the jQuery CDN:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

您可以在<head>部分中执行此操作,但是只要在jQuery代码之前加载就可以了.

You can do this within the <head> section, but it's fine as long as it's loaded before your jQuery code.

进一步阅读:

  • Why should I use Google's CDN for jQuery?
  • Microsoft CDN for jQuery or Google CDN?

将代码放在页面中

将您的代码放入<script>标记内.可以将其插入<head><body>中的任何位置.如果将其放在<input><tr>标记之前(如代码中所引用),则必须使用 $(document).ready() ,以确保在运行代码之前存在这些元素:

Place your code inside <script> tags. It can be inserted anywhere within either <head> or <body>. If you place it before the <input> and <tr> tags (as referenced in your code), you have to use $(document).ready() to make sure those elements are present before the code is run:

$(document).ready(function() {
    // put your jQuery code here.
});

如果您希望尽快加载页面内容,则可能希望将其放置在与</body> close标签尽可能近的位置.但是另一个常见的做法是将所有JavaScript代码放在<head>部分中.根据您的编码风格和需求,这是您的选择.

If you want your page content to be loaded as soon as possible, you might want to place it as close as the </body> close tag as possible. But another common practice is to place all JavaScript code in the <head> section. This is your choice, based on your coding style and needs.

建议:考虑将代码放在单独的.js文件中,而不是将JS/jQuery代码直接嵌入到HTML页面中.这将使您可以在其他页面上重复使用相同的代码:

Suggestion: Instead of embedding JS/jQuery code directly into an HTML page, consider placing the code in a separate .js file. This will allow you to reuse the same code on other pages:

<script src="/path/to/your/code.js"></script>

进一步阅读:

这篇关于如何将jQuery添加到HTML页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 15:20