使用jQuery的将桌面应用程序引入浏览器

2020-05-19 07:31:32易采站长站整理


清单 4. jQuery 解决冲突的办法




j$ = jQuery.noConflict();
j$(“div”).addClass(“a”);

选择

jQuery 的根本在于它在页面上选择和操作某些元素的能力。从某种意义上说,需要围绕这些对象才能构建出有效的 jQuery 库。因此,面对一个普通 HTML 页面上提供的大量选项,您需要一种方法来快速高效地选择您需要在页面上使用的元素,只选择需要的元素(不多也不少)。jQuery 如我们所愿地提供了一些强大的选择方法,帮助我们在页面上寻找和选择对象。jQuery 创建了它自己的选择语法,并且这种语法很容易掌握。

(以下大部分示例所使用的函数将留在下一篇中讨论,不过它们的功能应该是很直观明了的)。

根本上来讲,jQuery 中的选择过程就是一个巨大的过滤过程,页面上的每个元素都经过这个过滤器,它将返回一个匹配的对象,或一个可以遍历的匹配对象的数组。

排在前面的 3 个示例是最常用的。它们通过 HTML 标记、ID 或 CLASS 查找对象。

HTML

要获取一个页面中所有匹配的 HTML 元素的数组,您仅需将 HTML 标记(不带括号)传递到 jQuery 搜索字段。这是查找对象的 “快速但是粗糙” 的方法。如果要将属性附加到通用的 HTML 元素,这种方法是很有用的。


清单 5. HTML 选择

// This will show every <div> tag in the page. Note that it will show
// every <div>, not the first matching, or the last matching.
// Traversing Arrays is discussed later in the article.
$(“div”).show();

// This will give a red background to every <p> tag in the page.
$(“p”).css(“background”, “#ff0000”);


ID

正确的页面设置要求页面上的每个 ID 都是惟一的,虽然有时并不是这样(有意或无意)。使用 ID 选择时,jQuery 仅返回第一个匹配的元素,因为它要求您遵循正确的页面设计。如果您需要将一个标记附加到同一页面上的几个元素,应当选择使用 CLASS 标记。


清单 6. ID 选择 

// This will set the innerHTML of a span element with the id of “sampleText” to “Hi”.
// Note the initial “#” in the command. This is the syntax used by jQuery to search
// for IDs, and must be included. If it is excluded, jQuery will search for the HTML
// tag instead, and with no <sampleText> tags on a page, will ultimately do
// nothing, leading to frustrating and hard-to-find bugs (not that that has ever
// happened to me of course).