这是我的第一个问题:)
我已经从数组中动态创建了按钮,并尝试将onclick事件附加到每个按钮上。到目前为止,我还没有能够记录他们的任何反应。我如何定位集合中的特定按钮?
谢谢! `
var topics = ["Amy Winehouse", "Aretha Franklin", "Beyonce","Bjork", "Barbara Streisand", "Britney Spears", "Cher","Christina Aguilera", "Celine Dion", "Diana Ross","Donna Summer","Debbie Harry","David Bowie","Dolly Parton","Erykah Badu","Jennifer Lopez","Lana del Rey","Lady Gaga","Missy Elliot","Madonna","Mariah Carey","Shakira","Stevie Nicks","Whitney Houston"];
var buttons;
//function to create buttons
function divaBtns(){
for (var i=0; i < topics.length; i++){
buttons = $('<div></div>');
buttons.html("<input type='button' id='buttons' value='" + topics[i] + "'/>");
$("#btns").append(buttons);
}
}
divaBtns();
$('#btns').on('click', 'button', function(){
console.log("click");
});
<!DOCTYPE html>
<html>
<head>
<!--chart.js-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="./assets/giphy.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" href="./assets/style.css">
<title>Diva Gifs</title>
</head>
<body class="body">
<div class="container">
<div id="btns"></div>
<div id="gifs"></div>
</div>
</body>
</html>
`
答案 0 :(得分:2)
你的选择器错了。您附加了input
个元素,但这是选择buttons
:
$('#btns').on('click', 'button', function(){
console.log("click");
});
这对我有用:
$('#btns').on('click', 'input', function(e){
console.log("click: ", e.target.value);
});
var topics = ["Amy Winehouse", "Aretha Franklin", "Beyonce","Bjork", "Barbara Streisand", "Britney Spears", "Cher","Christina Aguilera", "Celine Dion", "Diana Ross","Donna Summer","Debbie Harry","David Bowie","Dolly Parton","Erykah Badu","Jennifer Lopez","Lana del Rey","Lady Gaga","Missy Elliot","Madonna","Mariah Carey","Shakira","Stevie Nicks","Whitney Houston"];
var buttons;
//function to create buttons
function divaBtns(){
for (var i=0; i < topics.length; i++){
buttons = $('<div></div>');
buttons.html("<input type='button' id='buttons' value='" + topics[i] + "'/>");
$("#btns").append(buttons);
}
}
divaBtns();
$('#btns').on('click', 'input', function(e){
console.log("click: ", e.target.value);
});
<!DOCTYPE html>
<html>
<head>
<!--chart.js-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="./assets/giphy.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" href="./assets/style.css">
<title>Diva Gifs</title>
</head>
<body class="body">
<div class="container">
<div id="btns"></div>
<div id="gifs"></div>
</div>
</body>
</html>
答案 1 :(得分:-1)
Selector&#39;#btns&#39;没有指向创建的按钮。 如下所示,可能会修改最后一行。
$('#btns input').on('click', function(){