我的html文件中有一个div,它有一个id ="按钮"我的目标是附加我的按钮数组。这样可行。然后,我如何使用jquery为每个按钮提供一个id,以便我可以单独定位它?
对于整体项目环境,我尝试做的是使用数组制作按钮。然后使用这些按钮,我将能够显示与点击按钮对应的GIF。即点击棒球和20个棒球GIF出现在页面上。
var topics = ["baseball", "hockey", "football", "basketball", "soccer",
"volleyball", "softball", "handball", "pickleball", "tennis"];
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + topics[0] +
"&api_key=dc6zaTOxFJmzC&limit=20";
$(document).ready(function(){
for (i = 0; i < topics.length; i++){
var buttons = topics;
$("#buttons").append("<button>" +buttons[i]+ "</button>");
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response){
console.log(response);
console.log(response.data[0].url)
});
}
});
答案 0 :(得分:1)
基本上你使用你的迭代器来使id不同:
var topics = ["baseball", "hockey", "football", "basketball", "soccer",
"volleyball", "softball", "handball", "pickleball", "tennis"];
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + topics[0] +
"&api_key=dc6zaTOxFJmzC&limit=20";
$(document).ready(function(){
for (i = 0; i < topics.length; i++){
var buttons = topics;
$("#buttons").append('<button id="topic_button_' + i + '">' +buttons[i]+ "</button>");
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response){
console.log(response);
console.log(response.data[0].url)
});
}
答案 1 :(得分:0)
您需要指定随机ID,或者您可以使用您的按钮名称作为ID将其设置为UNIQUE
$("#buttons").append("<button id="+buttons[i]+">" +buttons[i]+ "</button>");
或
$("#buttons").append("<button id="+buttons[i]+"_"+i+">" +buttons[i]+ "</button>");
答案 2 :(得分:0)
您可以在append
函数中包含ID:
append ("<button id='" + buttons[i] + "'>" + buttons [i] + "</button>")
答案 3 :(得分:0)
var topics = ["baseball", "hockey", "football", "basketball", "soccer",
"volleyball", "softball", "handball", "pickleball", "tennis"];
$(document).ready(function() {
// for every topic, append a button under #buttons
// save the topic name within the button, as data-topic attribute, for later use
for (i = 0; i < topics.length; i++) {
$("#buttons").append('<button data-topic="' + topics[i] + '">' + topics[i] + '</button>');
}
// click handler for buttons
$('#buttons > button').on('click', function() {
// time to use the saved topic from data-topics
var topic = $(this).data('topic');
// construct the url for this specific topic
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + topic +
"&api_key=dc6zaTOxFJmzC&limit=20";
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response){
console.log(response);
console.log(response.data[0].url)
});
});