简体   繁体   中英

Loading file with javascript/jquery

Here is the function I'm using:

jOWL.load("owldoc.owl", function(){});

jOWL.load takes in an owl document as a parameter (as seen above). I have 3 of these documents on the server, and would like the user to be able to chose which document to load by pressing a button.

I wonder if it is possible to have a string 'owldoc.owl', 'owldoc2.owl', or 'owldoc3.owl' passed to a javascript variable, which could then be passed in as a parameter to jOWL.load

How would I go about this?

Call the function below using onclick='loadFile("1"); return false;' onclick='loadFile("1"); return false;' inside of the respective link.

ie:

    <a href="" id='load1'>Load 1</a>
    <a href="" id='load2'>Load 2</a>
    <a href="" id='load3'>Load 3</a>

function:

    function loadFile(param){
        jOWL.load("owldoc"+param+".owl", function(){});
    }

To have onclicks that do not show up in line, the easiest way is to add ids to the anchors and call this function on page load using manageOnclicks(); :

    function manageOnclicks(){
        document.getElementById('load1').onclick = function(){loadFile('1'); return false;}
        document.getElementById('load2').onclick = function(){loadFile('2'); return false;}
        document.getElementById('load3').onclick = function(){loadFile('3'); return false;}
    }

Sample HTML

<input type='button' onclick="loadFile('owldoc.owl')" value='Load Owldoc'/>
<input type='button' onclick="loadFile('owldoc2.owl')" value='Load Owldoc2'/>
<input type='button' onclick="loadFile('owldoc3.owl')" value='Load Owldoc3'/>

Javascript

function loadFile(fileName) {
    // filename contains the variable
    // you can now do        
    //jOWL.load(filename, function(){}

}

Something like:

HTML:

<h3>Choose a file to load</h3>
<ul id='choose_file'>
    <li><a data-file='1'>File 1</a></li>
    <li><a data-file='2'>File 2</a></li>
    <li><a data-file='3'>File 3</a></li>
</ul>

JS

document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('#choose_file').addEventListener('click', function(evt) {
        var file_to_load = evt.target.getAttribute('data-file');
        jOWL.load('owldoc'+file_to_load+'.owl', function() {
            /* callback code here */
        });
    }, false);
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM