从<a>类标识的html标签中获取文本,并将其自动输入到另一个文本区域中



我有一个由WP插件生成的html标签,其中包含一个随机链接。 我需要拿起生成的链接并将其写入文本区域(从联系表单(,但需要它是自动的。

生成的包含链接的代码(无法更改(:

<p class="ozpital-wpwetransfer-success__url"><a 
href="we.tl/123">we.tl/123</a></p>

从文本区域编写代码以自动写入该链接:

<p><textarea class="wpcf7-form-control"></textarea></p>

我已经设法创建了一个带有按钮的解决方法,但它不好,我需要自动执行没有按钮的代码,如果我们运行代码,它将自动在文本区域中写入该链接。我也在尝试粘贴事件,但不必这样,我只是没有其他想法!

演示:https://jsfiddle.net/xf_analog/cgfwup90

我认为该演示是不言自明的,将感谢所有帮助。谢谢

如果该元素是动态生成的,您可以尝试执行以下操作:

window.onload = ()=>{
let link;
let linkValue = '';
let textArea = document.querySelector('textarea.wpcf7-form-control');

// generate the paragraph that has the link after 5 seconds
setTimeout(()=>{
// the containing paragraph
let paragraph = document.createElement('p');
// the anchor element that will be containing the link we want
let anchor = document.createElement('a');
let textNode = document.createTextNode('I am the target');
anchor.appendChild(textNode);
anchor.setAttribute('href', 'we.tl/123');
paragraph.classList.add("ozpital-wpwetransfer-success__url");
paragraph.appendChild(anchor)
document.body.appendChild(paragraph);
}, 5000);

// check if the anchor element exists then grab the value of its
// href attribute
setInterval(()=>{
// grab the anchor element inside the containing paragraph
link = document.querySelector('p.ozpital-wpwetransfer-success__url a');
// get the value of the element above
if(link){
linkValue = link.getAttribute('href');
}
// update the textarea's value if and only if the link is not in its own value
if(linkValue !== '' && textArea.value.indexOf(linkValue) == -1){
textArea.value = link.getAttribute('href')
}
}, 1000)
};
<html>
<body>
<p><textarea class="wpcf7-form-control"></textarea></p>
</body>
</html>

另外,这里有一个工作示例。:)

试试这个简单的,

.HTML

<a href="google.com" class="aa">ff</a>
<textarea class="tt"></textarea>

杰奎里

$(document).ready(function() { let link = $(".aa").attr("href"); $(".tt").val(link); });

最新更新