最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

call a javascript function inside a div - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Oct 23, 2012 at 21:49 The Alpha 146k29 gold badges293 silver badges311 bronze badges asked Oct 23, 2012 at 21:03 FabianFabian 5,6504 gold badges37 silver badges49 bronze badges 2
  • 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 different name. There is no "div-scope" in Javascript ;) – connexo Commented Jun 7, 2015 at 5:45
  • Find a working solution in my answer below. – connexo Commented Jun 7, 2015 at 5:54
Add a comment  | 

6 Answers 6

Reset to default 2

Why are you defining scripts in the divs?

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

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. ​

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.

<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 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.

发布评论

评论列表(0)

  1. 暂无评论