简体   繁体   中英

call a javascript function inside a div

I would like to create a webpage which contains several divs each containing the same draw function with different implementation (like a generic interface). After loading the page I want to iterate through all the divs and call each draw function one after the other.

My page so far looks like this:

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
  <script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
</head>
<body>

  <script type='text/javascript'>
    $( document ).ready( function() {
      // Draw all slots
      $('div.slot').each(function(i, d) {
        console.log('slot found: ' + d.id);
        // d.draw() does not work
        draw();
      });
    });
  </script>

  <div class="slot" id="slot1">
    <script type='text/javascript'>
      function draw() {
        console.log('Here we draw a circle');
      };
    </script>
  </div>

  <div class="slot" id="slot2">
    <script type='text/javascript'>
      function draw() {
        console.log('Here we do something totally different and draw a rectangle');
      };
    </script>
  </div>

</body>
</html>

Unfortunately I don't know how to call the draw function of the selected div "d". Right now it only calls the last defined draw function.

Update:

Mind you that I can not combine the different draw methods into one which would get a parameter like shape handed in. The draw methods will be totally independent from each other.

You can call it like

HTML:

<div class="slot" id="slot1">Draw1</div>
<div class="slot" id="slot2">Draw2</div>

JS:

function draw()
{
    console.log('Drawed! '+$(this).attr('id'));
}

$(document).ready( function() {
    $('div.slot').each(function(i, d) {
        console.log('slot found: ' + d.id);
        draw.call($(this));
    });
});

An Example .

Why are you defining scripts in the div s?

Do your logic all in one script block:

<head>      
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
</head>
<body>

  <script type='text/javascript'>
    $( document ).ready( function() {
      // Draw all slots
      $('div.slot').each(function(i, d) {
        console.log('slot found: ' + d.id);
        // d.draw() does not work
        draw();
      });
    });

    function draw(behavior) {
        console.log(behavior);
    }
  </script>

  <div class="slot" id="slot1" data-behavior="drew 1">
  </div>

  <div class="slot" id="slot2" data-behavior="drew 2">
  </div>

</body>
</html>

If you're looking to do something more complicated, you should consider building an object oriented javascript application, with each block's functionality derived from a class "slot".

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript

The reason that is happening is because you keep overwriting the draw function. Why don't you have a script page where you hold an array of function pointers to the right function like so:

var array = (draw1, draw2, draw3, ...);

function draw1()
{
    //do your thing on div1
}

...

function drawn()
{
    //do your n thing on divn
}

Now for your first div you need to call draw1 which is located at index 1 of the array.

HTML:

<div id="draw1">

</div>
....
<div id="drawn">

What do ya think. Note sytax has not been tested.

The easiest way I've found to go 'real OOP' in this case is to dispatch all on events on document level :

create a simple object and load this object in the main and the views like :

var events = {someCustomEventFromMain:'someCustomEventFromMain', someCustomEventFromView:'someCustomEventFromView'}

Now you can trigger events on document with jQuery like

$(document).trigger(events.someCustomEventFromMain, somedata);

And you can listen from any view or div or else

$(document).on(events.someCustomEventFromMain, function(__e, __data){
      //___e is the event emitted from __e.target
      //__data is the data object you wish to pass with the event
      //do something when event occurs

});

So if every subscript listens to some event at document level, in your case 'drawEvent',that should do the trick. You can even pass a parameters in the data of the event, like 'circle'. Hope this helps.

<html>
<head>

<script>
    $(document).ready(
            function() {
                $('#show').call(callfun());
            });
</script>
</head>
<body>
<h:form>
  <div id="show" align="center">
    <script>
    function callfun(){
    var data = "hi";
   alert(data);
  }
  </script></div>
    </h:form>
  </body>
  </html>

I think it may work.

Problem

You keep overwriting window.draw() every time you redefine it. You either need to namespace each one (that is, attach it to an (otherwise empty) object), or to give each and every function a distinct name. There is no "div-scope" in Javascript ;)

Solution

You can name each function according to the div 's id and call it dynamically using the object["methodName"]() syntax to call it.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <html> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script> </head> <body> <script type='text/javascript'> $( document ).ready( function() { // Draw all slots $('div.slot').each(function(i, d) { console.log('slot found: ' + d.id); // d.draw() does not work window[d.id]; }); }); </script> <div class="slot" id="slot1"> <script type='text/javascript'> function slot1() { console.log('Here we draw a circle'); }; </script> </div> <div class="slot" id="slot2"> <script type='text/javascript'> function slot2() { console.log('Here we do something totally different and draw a rectangle'); }; </script> </div> </body> </html> 

http://jsbin.com/mogeluzicu/1/edit?html,console

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