كيفية ربط كائنين مستندين بوظيفة jQuery واحدة

StackOverflow https://stackoverflow.com/questions/2542542

  •  23-09-2019
  •  | 
  •  

سؤال

لدي وظيفة jQuery مخصصة أحتاج إلى ربط كائنين مستند اثنين من iFrame.

حاليًا ستعمل مع واحد فقط يفعل شيئًا مثل:

$(window.frames["iframeName"].document).bind('textselect', function(e) {

});

ما أتطلع إلى فعله هو شيء مثل:

$(window.frames["iframeName"].document,window.frames["iframeName2"].document).bind('textselect', function(e) {

});

لا يوجد حل صحيح

نصائح أخرى

يمكنك تحويل الوظيفة المجهولة إلى واحدة مسماة واستخدامها لكلا الربطين ، مثل هذا:

$(window.frames["iframeName"].document).bind('textselect', selectStuff);
$(window.frames["iframeName2"].document).bind('textselect', selectStuff);

function selectStuff(e) {
  //Stuff
}

بدلاً من استخدام دالة مجهولة - قم بإنشاء دالة مسموحة

function myhandler(e)
{
    //body of function
}

ثم استخدم الوظيفة المسماة:

$(window.frames["iframeName"].document).bind('textselect', myhandler);
$(window.frames["iframeName2"].document).bind('textselect', myhandler);

بديل آخر

<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>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top