我有一个ID为“ test”和按钮的div。当我单击一个按钮时,将创建一个新的div,其ID为“ new”,其中包含一个h2元素。现在,当我单击新创建的h2元素时,我将向其添加输入表单。我的问题是,当我单击创建的输入框时,h2的onClick再次被调用,我不想这样做。 stopPropagation似乎也不起作用。请帮助我。
HTML
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="myscripts.js"></script>
</head>
<body>
<div id="test"></div>
<button type="button" id="b" class="btn btn-primary">Primary</button>
</body>
</html>
jquery:
$(document).ready(function(){
$("#b").click(function(){
var html = '<div id="new"><h2>Hi</hi></div>';
$('#test').append(html);
});
$("#test").on('click', "#new", function(e){
var html = '<input type="text" class="form-control search">';
$(this).append(html);
});
$("#test").on("keyup", ".search", function(event){
event.stopPropagation();
console.log('yes');;
});
});
答案 0 :(得分:1)
您正在为stopPropagation
事件而不是keyup
呼叫click
。
$(document).ready(function() {
$("#b").click(function() {
var html = '<div id="new"><h2>Hi</hi></div>';
$('#test').append(html);
});
$("#test").on('click', "#new", function(e) {
var html = '<input type="text" class="form-control search">';
$(this).append(html);
});
$("#test").on("keyup", ".search", function(event) {
event.stopPropagation();
console.log('yes');;
}).on('click', '.search', function(event) {
event.stopPropagation();
});
});
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="myscripts.js"></script>
</head>
<body>
<div id="test"></div>
<button type="button" id="b" class="btn btn-primary">Primary</button>
</body>
</html>