<a href="http://example.com">
<p>select this text</p>
<img src="" alt="">
</a>
Need to be able to copy text from p tag. The problem that p and img inside a and I can't select it.
I need exactly this HTML structure, as user should be able to copy link from that block. How can I do that?
答案 0 :(得分:1)
如果您要求纯JavaScript的解决方案,我猜这可行吗?
var els = document.querySelectorAll("a[href='http://example.com']");
console.log(els[0].textContent);
使用jQuery可能更简单
答案 1 :(得分:1)
这不是正确使用
block-level
元素作为inline
元素的子元素。
在你的情况下,使用像这样的jQuery:
var copyStr = $('a[href="http://example.com"] > p').text();
答案 2 :(得分:0)
使用textcontent
属性
func main() {
ch := make(chan int)
go func() {
select {
case <-ch:
log.Printf("1.channel")
default:
log.Printf("1.default")
}
select {
case <-ch:
log.Printf("2.channel")
}
close(ch)
select {
case <-ch:
log.Printf("3.channel")
default:
log.Printf("3.default")
}
}()
time.Sleep(time.Second)
ch <- 1
time.Sleep(time.Second)
}
&#13;
const a = document.querySelector('a');
console.log(a.textContent);
&#13;
答案 3 :(得分:0)
您可以使用Javascript execCommand("copy")
执行此操作,请参阅评论中解释:
function CopyText() {
/* Select Text inside p tag using createTextRange() */
if (document.selection) { // IE
var range = document.body.createTextRange();
range.moveToElementText(document.querySelector('#copytext p'));
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.querySelector('#copytext p'));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
/* Copie the Text inside the input to Clipboard */
document.execCommand("copy");
/* Alert success */
alert("Url Copied to Clipboard")
}
img {
width: 100%
}http://example.com
<a href="javascript:void(0)" id="copytext" onclick="CopyText()">
<p>http://example.com</p>
<img src="https://i0.wp.com/wptavern.com/wp-content/uploads/2016/07/stack-overflow.png?ssl=1" />
<input type="text" id="copy" style="opacity:0;height:0;width:0" />
</a>
答案 4 :(得分:0)
只需定义一个id为p标签,然后使用id如下所示拉出p标签内的文本:
$(document).ready(function(){
var par = $('#pid').text();
console.log(par)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<a href="http://example.com">
<p id="pid">...</p>
<img src="" />
</a>