使用 jQuery 为属性设置新值
本文将演示如何使用 jQuery 为属性设置新值。
使用 jQuery 为属性设置新值
attr()
操作设置或返回已选择组件的属性和值。当用于替换属性值时,该函数传递第一个匹配元素的值。
此方法在用于设置属性值时为匹配项的集合设置一个或多个属性/值对。
语法:
$(selector).attr(attribute_name, new_value)
这里使用的 attr()
方法用于为属性设置一个新值,它接受属性名称和值等参数。
例子:
<html>
<head>
<title>Set New Attribute</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#naya").attr("href", "https://www.youtube.com/");
});
});
</script>
</head>
<body>
<p><a href="https://www.google.com/" id="naya">ATT_Link</a></p>
<button>new value</button>
<p>
first, you can view the link and then click on button new value. it will
change the attribute value.
</p>
</body>
</html>
上面的示例显示属性的名称是 href
,其新值是指向 youtube 的链接。选择器是一个设置了新值的标签。
这里使用的选择器是 naya
,即带有 href
的角度标签的 id。当你在浏览器中运行此代码时,你将看到以下内容:
在这里,你可以看到一个链接和一个按钮。当你第一次单击该链接时,它将打开 google.com
,如代码中所述。
之后,当你单击名为 new value
的按钮时,你会看到属性 href
的初始值更改为 youtube.com
。点击按钮后,会触发 click
函数,然后借助 attr()
方法更改属性值。
看看下面的截图:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。