Skip to content

Instantly share code, notes, and snippets.

@ababup1192
Created August 23, 2017 06:29
Show Gist options
  • Save ababup1192/5f080616d6a8fb83b4900d24a67fee2f to your computer and use it in GitHub Desktop.
Save ababup1192/5f080616d6a8fb83b4900d24a67fee2f to your computer and use it in GitHub Desktop.
jQuery, new DOM event.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<!--[if lt IE 9]>
<script src="//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<link rel="shortcut icon" href="">
</head>
<body>
<input id="clone_btn" value="clone" type="button"></input>
<!-- 新しく作られるボタンのテンプレート。display: none; で、隠しておく。 -->
<div class="btn_template" style="display: none;">
<input class="cloned_btn" value="click here!" type="button"></div>
</div>
<div class="new_btns"></div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="./main.js"></script>
</body>
var counter = 0;
$("#clone_btn").click(function(){
// div.btn_template から .cloned_btnをクローン。
$clone_btn = $(".btn_template .cloned_btn").clone();
// 新しいクラス名を設定する。
var newClass = "new_btn_" + counter;
$clone_btn.addClass(newClass);
// ボタンが作られた(追加された)タイミングで、クリックイベントを設定する。
$clone_btn.click(function(){
// ボタン(クラス)によって、振る舞いが異なる。
// 今回の場合は、couter変数により名前が変わっていく。
alert(newClass);
});
counter++;
// div.new_btns に ボタンを追加
$clone_btn.appendTo(".new_btns");
});
/*
この時点では、ボタン(DOM)が作られていない為、
新しいボタンに対するクリックイベントは設定出来ない。
$clone_btn.click(function(){
alert("hogehoge");
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment