jQuery: working within iframe without re-linking
Maybe the title is a little misleading and question could be too, but I'm curious, how would one work with jQuery from an internal (same host/domain) iframe
without re-linking to jQuery's source in iframe's loaded HTML.
Well, I'm able to access it with parent.jQuery();
, but whenever I'm tryin开发者_开发百科g to manipulate elements with it, it works in parent
frame not the current, active one.
Iframe is generated with ColorBox v.1.3.16
.
Here is what I've tried so far, with no luck at all.. (this comes from within iframe):
jQuery = parent.jQuery;
jQuery(document).ready(function(){
jQuery('#time-bar .slider', document).css({ 'background-color' : 'blue', 'left' : '-99%' });
});
I've used document
as a parent selector here, but it doesn't work, and I have no idea what should be used there.
Thanks in advance!
EDIT:
Derived from T.J. Crowder:
parent.jQuery(function($) {
var element = $("#time-bar", document);
console.log(element);
});
console.log()
returns an empty object, or actually, have no idea if it can be called an object: []
.
Barring other factors, your code passing in document
to the jQuery()
($()
) function as the context document should work.
Example:
HTML:
<script src="blah/blah/jquery.min.js"></script>
<iframe id='theframe' src='http://jsbin.com/ulehi4'>
iFrame HTML:
<input type='button' id='theButton' value='Click Me'>
iFrame JavaScript:
parent.jQuery(function($) {
$("#theButton", document).click(function() {
$("<p>Button clicked!</p>").appendTo(document.body);
});
});
Live example
That said, though, if you use the same exact link to the jQuery file (perhaps from one of the CDNs it's in) in both the parent and the frame, there's very little overhead indeed. You can insert a script
element in the iframe if you're not in control of the markup.
If I understand the question correctly - see: jQuery/JavaScript: accessing contents of an iframe
more importantly from there:
$().ready(function () { $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading $('some selector', frames['nameOfMyIframe'].document).doStuff(); }); };
精彩评论