[英]How can I grab a clicked word in an iframe src with js?
This js allows copying a clicked word in an html element to var "str".此 js 允许将 html 元素中的点击单词复制到 var "str"。 But I want to grab a word in an iframe src.
但我想在 iframe src 中抓取一个单词。 I modified the js to target the iframe id #USCF_CUST and grab the clicked word, but it doesn't seem to work.
我修改了 js 以定位 iframe id #USCF_CUST 并抓取点击的单词,但它似乎不起作用。 The clicked word is not selected and copied to var "str".
单击的单词未选择并复制到 var "str"。 Can anyone tell me why?
谁能告诉我为什么?
<div class = "clickable">The rain in Spain falls mainly in the plane.</div>
$(".clickable").click(function(e) {
s = window.getSelection(); var range = s.getRangeAt(0); var node = s.anchorNode;
while (range.toString().indexOf(' ') != 0) {range.setStart(node, (range.startOffset - 1));}
range.setStart(node, range.startOffset + 1);
do {range.setEnd(node, range.endOffset + 1);}
while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '');
str = range.toString().trim(); alert (str);
});
But the above js doesn't work (it does nothing) in this instance:但是在这种情况下,上面的 js 不起作用(它什么也不做):
<iframe id = 'USCF_CUST' src= url_2 ></iframe>
$("#USCF_CUST").click(function(e) {
s = window.getSelection(); var range = s.getRangeAt(0); var node = s.anchorNode;
while (range.toString().indexOf(' ') != 0) {range.setStart(node, (range.startOffset - 1));}
range.setStart(node, range.startOffset + 1);
do {range.setEnd(node, range.endOffset + 1);}
while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '');
str = range.toString().trim(); alert (str);
});
When you write window
you reference the window where the code is executed.当您编写
window
时,您将引用执行代码的窗口。 However, it seems like you want to reference iframe
s window
.但是,您似乎想引用
iframe
的window
。
Try using contentWindow
property of iframe in order to set listeners, getSelection
, etc.尝试使用 iframe 的
contentWindow
属性来设置侦听器、 getSelection
等。
It will only work if the origin of both pages is exactly the same.只有当两个页面的来源完全相同时,它才会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.