我在JavaScript和HTML中添加了2個元素到我的數組中,我想添加一個副本到剪貼板按鈕作爲每個數組的新元素,但我很努力地做這是由於複雜的代碼。 這裏是我的代碼如何在JavaScript中添加一個新的元素到數組中的數組
var currImage = 0;
window.onload =() => {
const factsArr = [
\t { image:'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif', source:"<a href='http://news.nationalgeographic.com/news/2010/03/100315-half-male-half-female-chickens/' style='text-decoration:none;color:#FFFFFF;' target='_blank'>know more</a>",},
\t { image:'https://media.giphy.com/media/1nkUav308CBws/giphy.gif', source:"<a href='http://www.guinnessworldrecords.com/world-records/most-expensive-pizza' style='text-decoration:none;color:#FFFFFF;'target='_blank'>know more</a>"},
]:
const swtch =() => {
document.getElementsByClassName('image')[0].setAttribute('src', factsArr[currImage].image);
document.getElementsByClassName('source')[0].innerHTML=factsArr[currImage].source;
\t document.getElementById('copyToClipboard').innerHTML=copyToClipboard(element).copyToClipboard
currImage++;
if (currImage == factsArr.length)
currImage = 0;
console.log(currImage);
};
document.getElementsByClassName('generate-btn')[0].addEventListener('click', swtch);
document.getElementsByClassName('source')[0].addEventListener('click', swtch);
}
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="generate-btn">Amazing Fact Button</button>
<div class="source"></div>
<img class="image" />
<button onclick="copyToClipboard('element')">Copy Link</button>
你有一些錯誤1. document.getElementsById( 'copyToClipboard')的innerHTML = copyToClipboard(元素).copyToClipboard - 元素沒有定義。 2. document.getElementsById('copyToClipboard')。innerHTM - 它應該是document.getElementById('copyToClipboard')。innerHTML – Lalit