Uncaught TypeError: Cannot use 'in' operat

2019-09-14 15:46发布

问题:

I've got a problem with this code snippet:

<script>
                $.sap.require('sap.ui.thirdparty.jqueryui.jquery-ui-core');
                $.sap.require('sap.ui.thirdparty.jqueryui.jquery-ui-widget');
                $.sap.require('sap.ui.thirdparty.jqueryui.jquery-ui-mouse');
                $.sap.require('sap.ui.thirdparty.jqueryui.jquery-ui-draggable');
                $.sap.require('sap.ui.thirdparty.jqueryui.jquery-ui-sortable');
        </script>
        <script>
                jQuery.sap.includeStyleSheet("resources/css/dashboard.css");
                sap.ui.localResources("dashboard");
                var view = sap.ui.view({id:"idHome1", viewName:"dashboard.Home", type:sap.ui.core.mvc.ViewType.JS});
                view.placeAt("content");
        </script>
        <script>
            var oButton = sap.ui.getCore().byId("oChart_Button");
            console.log(oButton);
            $(document).ready(function(){
                $(oButton).draggable({
                    cancel: false
                })
            })
        </script>

I can't drag my button, because of the ErroMessage in the title. I've got this example from the internet, and for the people who comment this blog the code runs. The button exists, with console.log(oButton) I get a message with it's properties and so on. Any one a solution?

回答1:

Use getDomRef to get DOM element of your UI5 control. So, your code will be something like this.

var oButton = sap.ui.getCore().byId("oChart_Button");
var el = oButton.getDomRef();
$(el).draggable({
    cancel: false
});

jQuery selectors allow you to select and manipulate HTML element(s). When you do $(oButton) you are passing SAPUI5 Button object to jQuery selector, which will not work. So, to get respective HTML DOM element of UI5 Button control, getDomRef is used.

So, why your button is not draggable even after passing DOM to jQuery selector?

This might be happening because first you are loading third party library for jQuery-Ui for draggable functionality. Then, after that SAPUI5 library is loaded, so functions only from SAPUI5 library are available. So, to overcome this, we can load the third party library after UI5 library within body of your HTML file.