如何在JavaScript/jQuery中改变一个img元素的src属性
任务是通过使用JQuery和JavaScript来改变<img>
元素的src属性。
- jQuery prop()方法。这个方法设置/返回匹配元素的属性和值。如果这个方法是用来返回属性值,它返回第一个被选中的元素的值。如果此方法用于设置属性值,它为所选元素集设置一个或多个属性/值对。
语法:
- 返回一个属性的值。
$(selector).prop(property)
- 设置属性和值。
$(selector).prop(property, value)
- 使用一个函数设置属性和值。
$(selector).prop(property, function(index, currentvalue))
- 设置多个属性和值。
$(selector).prop({property:value, property:value, ...})
参数:
- property。这个参数指定了属性的名称。
- value。这个参数指定属性的值。
- function(index, currentvalue):这个参数指定一个函数,返回要设置的属性值。
- index。该参数接收元素在集合中的索引位置。
- currentValue:该参数接收选定元素的当前属性值。
- jQuery on()方法。这个方法为选定的元素和子元素添加一个或多个事件处理程序。
语法:
$(selector).on(event, childSelector, data, function, map)
参数:
- event。这个参数是必需的。它指定了一个或多个事件或命名空间,以附加到选定的元素。在有多个事件值的情况下,这些值用空格分隔。事件必须是一个有效的。
- childSelector。这个参数是可选的。它指定了事件处理程序应该只附加到定义的子元素。
- data。这个参数是可选的。它指定了要传递给函数的额外数据。
- function。这个参数是必需的。它指定了事件发生时要运行的函数。
- map。它指定了一个事件地图(
{event:func(), event:func(), ...}
),有一个或多个事件添加到选定的元素,以及事件发生时要运行的函数。
例子1:这个例子通过使用JavaScript改变图片的src属性。
<!DOCTYPE HTML>
<html>
<head>
<title>
Change the src attribute
of an img tag
</title>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;">
</p>
<img id = "img" src =
"https://media.geeksforgeeks.org/wp-content/uploads/20190529122828/bs21.png" />
<br>
<button onclick = "GFG_Fun()">
click here
</button>
<p id = "GFG_DOWN" style =
"color:green; font-size: 20px; font-weight: bold;">
</p>
<script>
var up = document.getElementById('GFG_UP');
up.innerHTML = "Click on button to change the src of image";
var down = document.getElementById('GFG_DOWN');
function GFG_Fun() {
document.getElementById("img").src =
'https://media.geeksforgeeks.org/wp-content/uploads/20190529122826/bs11.png';
down.innerHTML = "src attribute changed";
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
实例2:这个例子通过使用JQuery改变图片的src属性。
<!DOCTYPE HTML>
<html>
<head>
<title>
Change the src attribute of
an img tag using jQuery
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;">
</p>
<img id = "img" src =
"https://media.geeksforgeeks.org/wp-content/uploads/20190529122828/bs21.png" />
<br>
<button onclick = "GFG_Fun()">
click here
</button>
<p id = "GFG_DOWN" style =
"color:green; font-size: 20px; font-weight: bold;">
</p>
<script>
("#GFG_UP").text("Click on button to change the src of image");
('button').on('click', function(e) {
('#img').prop('src',
'https://media.geeksforgeeks.org/wp-content/uploads/20190529122826/bs11.png');
("#GFG_DOWN").text("src attribute changed");
});
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。