How to bind two document objects to single jquery function
I have a custom jquery function that I n开发者_运维技巧eed to bind to two iframe document objects.
Currently it will work with just one doing something like:
$(window.frames["iframeName"].document).bind('textselect', function(e) {
});
what I'm looking to do is something like:
$(window.frames["iframeName"].document,window.frames["iframeName2"].document).bind('textselect', function(e) {
});
You can convert the anonymous function to a named one and use it for both binds, like this:
$(window.frames["iframeName"].document).bind('textselect', selectStuff);
$(window.frames["iframeName2"].document).bind('textselect', selectStuff);
function selectStuff(e) {
//Stuff
}
Instead of using an anonymous function - create a named function
function myhandler(e)
{
//body of function
}
Then use the named function:
$(window.frames["iframeName"].document).bind('textselect', myhandler);
$(window.frames["iframeName2"].document).bind('textselect', myhandler);
Another alternative
<body>
<iframe name="iframe1" src="text.html" width="100px" height="100px" style="border:1px solid #000"></iframe>
<iframe name="iframe2" src="text.html" width="100px" height="100px" style="border:1px solid #000"></iframe>
<script type="text/javascript">
$(document).ready(function() {
function bindFrameDocuments(eventType, handler) {
for (var i = 0; i < window.frames.length; i++) {
$(window.frames[i].document).bind(eventType, handler);
}
}
bindFrameDocuments(
'textselect',
function(e) {
// this function runs in the scope of the frame
window.parent.console.log(e);
}
);
});
</script>
</body>
精彩评论