JavaScript/jQuery
【jQuery/Selector #10】:button
1Q74
2023. 2. 21. 23:23
1. Description
모든 button Element들을 찾는다.
$(":button")은 CSS의 $( "button, input[type='button']" )과 같다고 한다.
속도 향상을 위해서는 직접 $(":button") Selector를 사용하기 보다는, pure CSS Selector를 사용한 후에 .filter(":button")을 사용하는 것이 좋다고 한다.
※ 자세한 내용은 「5. Reference」를 참고하세요.
2. Example
#1버튼을 클릭하면 button Element를 찾아 border-color, border-size를 변경한다. 버튼을 클릭할 때마다 해당 CSS가 토글된다.
buttons
link-1[HTML Code]
[//HTML Code]
3. Code
더보기
<!-- ---------------------------------------------------------
--
-- Author: 1q74.tistory.com
--
--------------------------------------------------------- -->
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>[1q74.tistory.com] javascript/jquery/selector/:button</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
<div name="_1q74-example-root">
<div name="_1q74-example-1">
<h4>buttons</h4>
<input type="button" name="button-1" value="2utton-1"/>
<a href="#">link-1</a>
<button name="button-2">Button-2</button>
<input type="text" name="user-id" value="This is User Id"/>
</div>
<div name="_1q74-example-bottom">
<br/>
<button name="btn-execute">#1. $("[name='_1q74-example-1'] :button")</button>
</div>
</div>
<hr/>
<h5>[HTML Code]</h5>
<div name="_1q74-source">
</div>
<h5>[//HTML Code]</h5>
<script>
const btnExecute = $("[name='btn-execute']");
const button = $("[name='_1q74-example-1'] :button");
btnExecute.click(function() {
const isNotStyled = (button.css("border-color") === "rgb(0, 0, 0)");
const styles = {
"border-color": "blue",
"border-size": "2px"
};
$.each(styles, function(key, value) {
if(isNotStyled) {
button.css(key, value);
} else {
button.css(key, "");
}
});
});
// ------------------------------------------------------
// 소스출력
// ------------------------------------------------------
var textSource = $("[name='_1q74-source']");
var exampleHtml = $("[name='_1q74-example-root']").html();
var specialCharLines = textSource.text(exampleHtml).html().split("\n");
textSource.html(specialCharLines.join("<br/>").replaceAll("\t", " "));
</script>
<style>
[name="_1q74-example-bottom"] button
,[name="_1q74-source"] button {
background: lightgray;
border: 5px outset;
min-height: 30px;
}
[name="_1q74-example-bottom"] button:active
,[name="_1q74-source"] button:active {
border: 2px inset;
min-height: 30px;
}
</style>
</body>
</html>
4. File
[javascript][jquery][selector]button.html
0.00MB
5. Reference
https://api.jquery.com/button-selector/