【发布时间】:2017-06-15 16:44:31
【问题描述】:
我有这个函数叫copyToClipboard()。这需要一个名为 element 的参数。此函数通过定位元素的 id、选择和复制内容来复制元素的内容。
例如:
JS
/*
* Copy to clipboard fn
*/
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
var $tempval = $temp.val($(element).text());
$temp.remove();
var $notif = $("<p>");
$notif.attr("class","notif");
$("body").append($notif);
$notif.html('Copied content to clipboard!');
setTimeout(function() {
$notif.fadeOut();
$notif.promise().done(function(){
this.remove();
});
}, 400);
}
HTML:
<p id="p1">content of #p1</p>
<p> not me tho </p>
<p id="p2">content of #p2</p>
<button onclick="copyToClipboard('#p1')">Copy P1</button>
<button onclick="copyToClipboard('#p2')">Copy P2</button>
我正在尝试将其改进为动态生成按钮的功能。
到目前为止,我的方法是将上述函数集成到一个新函数中,迭代由 ID/Class(本例中为 ID)找到的元素,vb 使用 onclick 函数容器生成按钮,将迭代值作为参数/参数.
/*
* generate copy buttons fn
*/
function generateCopyButtons() {
var links = document.getElementById('links').getElementsByTagName('p');
for (var i = 0; i < links.length; i++) {
var $link = links[i];
var thisId = $($link).attr('id');
if( thisId && thisId !== "null" && thisId !== "undefined" ){
var $button = document.createElement('button'); // btn
$button.innerHTML = 'Copy ' + thisId; //btn text
var element = '#' + thisId; // # + id
// console.log(element); // works like i want, #p1, #p2
//how do i pass the element into this function??
$button.onclick = function(element) {
var $temp = $("<input>");
$temp.val($(element).text()).select();
document.execCommand("copy");
var $tempval = $temp.val($(element).text());
$("body").append($temp);
$temp.remove();
var $notif = $("<p>");
$notif.attr("class","notif");
$("body").append($notif);
$notif.html('Copied content to clipboard!');
setTimeout(function() {
$notif.fadeOut();
$notif.promise().done(function(){
$notif.remove();
});
}, 400);
};
$($link).prepend($button);
// $($thisHashId).remove();
}
}
}
$(document).ready(function(){
generateCopyButtons();
});
现在它不显示错误并且它不起作用。使用前面的按钮效果很好。
【问题讨论】:
标签: javascript jquery dynamic parameters arguments