简体   繁体   English

在div中调用javascript函数

[英]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). 我想创建一个包含几个div的网页,每个div包含具有不同实现的相同绘制函数(如通用接口)。 After loading the page I want to iterate through all the divs and call each draw function one after the other. 加载页面后,我想遍历所有div并一个接一个地调用每个绘制函数。

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". 不幸的是我不知道如何调用所选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: HTML:

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

JS: 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? 你为什么要在div定义脚本?

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". 如果你想要做一些更复杂的事情,你应该考虑构建一个面向对象的javascript应用程序,每个块的功能都来自一个类“slot”。

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript 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. 现在为你的第一个div你需要调用draw1,它位于数组的索引1。

HTML: HTML:

<div id="draw1">

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

What do ya think. 你觉得怎么样? Note sytax has not been tested. 注意sytax尚未经过测试。

The easiest way I've found to go 'real OOP' in this case is to dispatch all on events on document level : 在这种情况下,我发现“真正的OOP”的最简单方法是在文档级别上发送所有事件:

create a simple object and load this object in the main and the views like : 创建一个简单的对象并在main和视图中加载此对象,如:

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

Now you can trigger events on document with jQuery like 现在,您可以使用jQuery触发文档上的事件

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

And you can listen from any view or div or else 而你可以从任何视图或div听取

$(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. 因此,如果每个下标在文档级别侦听某些事件,在您的情况下为'drawEvent',那应该可以解决问题。 You can even pass a parameters in the data of the event, like 'circle'. 您甚至可以在事件数据中传递参数,例如“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. 每次重新定义时,都会覆盖window.draw() 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 ;) Javascript中没有“div-scope”;)

Solution

You can name each function according to the div 's id and call it dynamically using the object["methodName"]() syntax to call it. 您可以根据divid命名每个函数,并使用object["methodName"]()语法动态调用它来调用它。

 <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 http://jsbin.com/mogeluzicu/1/edit?html,console

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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