简体   繁体   English

使用Javascript注入HTML

[英]Inject html using Javascript

I have to inject the following line of html to a document through javascript: 我必须通过javascript将以下html行注入文档中:

<button type='button'>btnName </button>

In addition to this, I have to register an onclick to the button where the function to be invoked expects an arg say 'arg' so the javascript looks something like this: 除此之外,我还必须在按钮上注册一个onclick,在该按钮上要调用的函数期望一个arg表示'arg'因此javascript如下所示:

var html = "<button type='button' onclick='+ fnName +
    "(the param shld go here)'>" + btnName + "</button>"

How do I achieve this? 我该如何实现? One obvious solution is to assign an Id to the button and then register a click function later on once the html is appended to the document. 一个明显的解决方案是将一个ID分配给按钮,然后在将html附加到文档之后注册一个click函数。 But I dont want to do this because there are too many buttons. 但是我不想这样做,因为按钮太多了。 Is there another option that you can think of. 您还有其他选择可以想到。

Addition: The function name is dynamic, and the 'arg' that goes in is also dynamic. 添加:函数名称是动态的,并且'arg''arg'也是动态的。 An Id if at all is required has to be autogenerated. 如果需要,则必须自动生成一个ID。

** **

I've got the solution, please see below 我有解决方案,请参阅下文

** **

I would recommend jquery. 我会推荐jQuery的。

Something like 就像是

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script>
$(document).append(
  $("input")
  .attr("type", "button")
  .click(function(){
    doSomething()
  ))
);
</script>

You should avoid using onclick as an HTML attribute. 您应该避免将onclick用作HTML属性。 Instead, create the button programmatically through the DOM interface and attach the event as a property. 而是通过DOM界面以编程方式创建按钮,并将事件作为属性附加。

var button       = document.createElement("button");
button.type      = "button";
button.innerHTML = btnName;
button.onclick   = function() {
    window[fnName](data);
};

// Insert the button into whatever container node you are populating
someContainerNode.appendChild(button);

Or the jQuery way since that's where the band wagon is going: 还是jQuery的方式,因为这是乐队旅行的方向:

$("<button type='button'>" + btnName + "</button>").click(function() {
    window[fnName](data);
}).appendTo(someContainerNode);

Also, since you are not setting the onclick handler as a string, you will not need to convert your function argument data to a JSON string, which will improve performance. 另外,由于您没有将onclick处理程序设置为字符串,因此不需要将函数参数data转换为JSON字符串,这将提高性能。

Since you don't want to assign an onclick method the usual ways, a round about way would be to have them all call a function with a unique identifying number. 由于您不想以通常的方式分配onclick方法,因此,一种解决方法是让它们全部调用具有唯一标识号的函数。 The function will have a two dimensional array that has the argument, this is assuming every button calls the same function with a different parameter. 该函数将具有一个带有参数的二维数组,这是假定每个按钮使用不同的参数调用同一函数。

Edit: I may have misunderstood, here is some code not using jQuery that I used in a recent project. 编辑:我可能有一个误解,这是一些代码使用我在最近的项目中使用的jQuery。

for(var place = 0; place < 5; place++)
        {
            if(document.getElementById('title_'+ place).addEventListener)//this is for compatablity
                document.getElementById('title_'+ place).addEventListener('click', function(e){/*some code*/});
            else if(document.getElementById('title_'+ place).attachEvent)
                document.getElementById('title_'+ place).attachEvent('onclick',  function(e){/*some code*/});
            else
                document.getElementById('title_'+ place) = function(e){/*some code*/};
        }

The code adds an onClick event to five objects, and since it checks which method works in the current browser, it supports the main browsers (as far as I have tested). 该代码将onClick事件添加到五个对象,并且由于它检查哪种方法在当前浏览器中有效,因此它支持主要的浏览器(据我所测试)。

I took out some code for readability but that was just the code in the functions that would be called. 我出于可读性取出了一些代码,但这只是要调用的函数中的代码。

you can use document.write for that variable. 您可以为该变量使用document.write。 var html = document.write('' + btnName + ''). var html = document.write(''+ btnName +'')。 Please correct the single and double quotes. 请更正单引号和双引号。 I dont know this is useful for you or not 我不知道这是否对您有用

if you dont want to bind an event to each individual button, you can bind one event to a parent of all those buttons (eg, the parent div holding the buttons for example), and then use event bubbling to achieve a similar effect. 如果您不想将事件绑定到每个按钮,则可以将一个事件绑定到所有这些按钮的父级(例如,持有该按钮的父级div),然后使用事件冒泡实现类似的效果。

eg 例如

<div id="parent">   
   <button id="b0">text</button>
   <button id="b1">text</button>
   <button id="b2">text</button>
   <button id="b3">text</button>
   <button id="b4">text</button>
   <button id="b5">text</button>
</div>
<script>
   $("#parent").click(function(e){
       if ($(e.target).attr("id") === "b0") {
          // do b0's stuff
       } else if ($(e.target).attr("id") === "b1") {
          //do b1's stuff 
       } //etc 
   });
</script>

another way to do it is to use jquery live events - they are essentially doing what i have written above (more elegantly of course). 做到这一点的另一种方法是使用jquery实时事件 -它们本质上是在做我上面写的事情(当然更优雅)。 As for the arguments, how do you obtain the arguments in the first place? 至于参数,您首先如何获得参数? without knowing that, i cant really tell you the best way forward. 不知道那一点,我真的不能告诉你最好的前进方向。

我已经解决了:-

var html = "<button type='button' onclick='"+ fnName +"("+ JSON.stringify(data) +")'>"+ btnName + "</button>"

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

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