我正在制作一个内部页面,以生成供员工发送给客户的付款链接。该工作人员应该能够输入一个25.99
之类的小数,并与https://example.com/pay/
组合成https://example.com/pay/25.99
<script>
function process() {
var copyText ="https://example.com/pay/" + document.getElementById("paylink").value;
copyText.select();
document.execCommand("copy");
alert("Copied the link: " + copyText.value);
}
</script>
<form onSubmit="return process();">
<p>Enter the amount as a decimal:</p><br>
<input type="text" name="url" id="url"> <input type="submit" value="Get Link" id="paylink">
</form>
我使用了其他版本来管理向用户发送URL的操作,但我希望避免工作人员访问这些URL并立即复制它。
任何帮助将不胜感激。预先感谢。
UPDATE: This clearly isn't a duplicate, if you read it you'd know that
答案 0 :(得分:1)
下面是您在jsfiddle中修改的代码,可以操纵输入框来执行复制。 (不确定何时会发起实际的后端通话,因此必须根据该情况进行调整)
https://jsfiddle.net/gowrimr/6vynm0rs/39/
<form onClick="return process();">
<p>Enter the amount as a decimal:</p><br>
<input type="text" name="url" id="url"> <input type="submit" value="Get Link" id="paylink">
</form>
<script>
function process() {
const amt = document.getElementById("url").value
var copyText ="https://example.com/pay/"+amt
document.getElementById("url").value=copyText
url.select();
document.execCommand("copy");
document.getElementById("url").value=amt
}
</script>
答案 1 :(得分:0)
建议使用How do I copy to the clipboard in JavaScript?迪恩·泰勒的答案。
JavaScript
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = 0;
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
function process() {
var copyText ="https://example.com/pay/" + document.getElementById("paylink").value;
copyTextToClipboard(copyText);
}
jQuery
function copyTextToClipboard(text) {
var textArea = $("<textarea">).css({
position: "fixed",
top: 0,
left: 0,
width: "2em",
height: "2em",
padding: 0,
border: "none",
outline: "none",
"box-shadow": "none",
background: "transparent",
value: text
}).appendTo($("body"));
textArea[0].focus();
textArea[0].select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
textArea.remove();
}
function process() {
var copyText ="https://example.com/pay/" + $("#paylink").val();
copyTextToClipboard(copyText);
}
希望有帮助。