[英]How to get the href attribute with clipboard.js?
我試圖在單擊按鈕后獲取href屬性,但無法使其工作。
我的代碼:
<!-- Target -->
<a href='https://clipboardjs.com/' id='foo'/>
<!-- Trigger -->
<button class='btn' data-clipboard-target='#foo'>
Copy to clipboard
</button>
<script type="text/javascript">
new Clipboard(".btn", {
text: function(trigger) {
return $(trigger).getAttribute("href");
}
});
</script>
有任何想法嗎?
謝謝
getAttribute
是一個本機DOM方法,您不能直接將其應用於jQuery包裝的元素。 您需要獲取本機DOM元素,或者使用jQuery的attr()
方法來獲取href
的值:
$(trigger)[0].getAttribute("href");
// OR
$(trigger).attr("href");
嘗試這個:
new ClipboardJS(".btn", { text: function(trigger) { const query = trigger.getAttribute('data-clipboard-target'); const target = document.querySelector(query); return target.getAttribute('href'); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js"></script> <!-- Target --> <a href='https://clipboardjs.com/' id='foo'></a> <!-- Trigger --> <button class='btn' data-clipboard-target='#foo'> Copy to clipboard </button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.