最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery and binding an event to an iframe - Stack Overflow

programmeradmin1浏览0评论

**I'm currently using a jquery textselect plugin to fire alerts based on the selection text anywhere on the page and it works just fine doing something like:

$(document).ready(function() {
    $(document).bind('textselect', function(e) {
        alert(e.text); 
    });
});

I've since had to add an iframe to the page and I need the text selection to work on text within the iframe as well. I'm trying to do something like this but it's not working:

$(document).ready(function() {
    $('#iframeId').load(function() {
    $(document.getElementById("iframeId").contentWindow).bind('textselect',function(e) {
    alert(e.text); 
    });
});

At this point I've tried a whole mess of ways to reference the iframe document without any success. Any ideas?**

**I'm currently using a jquery textselect plugin to fire alerts based on the selection text anywhere on the page and it works just fine doing something like:

$(document).ready(function() {
    $(document).bind('textselect', function(e) {
        alert(e.text); 
    });
});

I've since had to add an iframe to the page and I need the text selection to work on text within the iframe as well. I'm trying to do something like this but it's not working:

$(document).ready(function() {
    $('#iframeId').load(function() {
    $(document.getElementById("iframeId").contentWindow).bind('textselect',function(e) {
    alert(e.text); 
    });
});

At this point I've tried a whole mess of ways to reference the iframe document without any success. Any ideas?**

Share Improve this question asked Mar 26, 2010 at 21:02 dbrdbr 211 silver badge2 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You can access it like this:

$(document).ready(function() {
  $('#iframeId').load(function() {
    alert("Loaded");
    $('#iframeId').contents().find("body").bind('textselect', function(e) {
      alert(e.text);
    });
  });
});

Note: This only works if the iframe is loading something on the same domain, otherwise you're going to be blocked by the same origin policy.

Here's what I ended up doing just for reference... What you sent worked. The original function is passing in a document object. For an iframe document object I did something like:

window.frames["ifFrameName"].document
发布评论

评论列表(0)

  1. 暂无评论