Home  >  Article  >  Web Front-end  >  How to use click to change id in jquery

How to use click to change id in jquery

WBOY
WBOYOriginal
2022-05-09 10:50:421636browse

Method: 1. Use "element object.click(function(){event processing function})" to add a click event to the specified element and specify the event processing function; 2. In the event processing function, use " Element object.attr("id","changed id value");"Just set the changed id value.

How to use click to change id in jquery

The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.

How to use click to change the id in jquery

1. Bind the click event to the element

When the element is clicked, the click event occurs.

The click() method triggers a click event, or specifies a function to run when a click event occurs.

Syntax

Trigger the click event of the selected element:

$(selector).click()

Add a function to the click event:

$(selector).click(function)

2. Use the attr method to change id value

attr() method sets or returns the attributes and values ​​of the selected element.

When this method is used to return an attribute value, the value of the first matching element is returned.

When this method is used to set attribute values, one or more attribute/value pairs are set for the matching element.

Set attributes and values:

$(selector).attr(attribute,value)

Examples are as follows;

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>123</title>
<script src="js/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").attr("id","mydiv2");
});
});
</script>
<style>
#mydiv1{
background:#66ccff;
}
#mydiv2{
background:pink;
}
</style>
</head>
<body>
<div id="mydiv1" style="width:100px;height:100px;border:1px solid #000;"></div>
<br>
<button>为元素改变id属性</button>
</body>
</html>

Output results:

How to use click to change id in jquery

Recommended related video tutorials :jQuery video tutorial

The above is the detailed content of How to use click to change id in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn