2018.01.08
カテゴリ:PHP
jQueryでh1と最初のh2の内容(text)を入れ替える
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>jQuery TIPS</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<h1>H1のあああああああああああああ</h1>
<h2>H2のaaaaaaaaa</h2>
適当な文章のサンプル
<h2>H2のbbbbbbbbbbbbb</h2>
<h2>H2のccccccccccccc</h2>
<h2>H2のdddddddddddddddddd</h2>
<hr>
最初のh2とh1の文字を入れ替える : <input type="button" value="test実行" id="testbtn">
<script>
$(function() {
});
$("#testbtn").click(function(){
//alert("test");
var h1=$("h1").text();
var firsth2="";
$("h2").each(function(i,elem) {
//alert(i+":"+$(elem).text());
if (i==0) {
firsth2 = $(elem).text();
$(elem).text(h1);
}
});
if (firsth2 != "") {
$("h1").text(firsth2);
}
});
</script>
</body>
</html>
「test実行」をクリックすると以下の様になり、再度押すと戻る。