+ -
当前位置:首页 → 问答吧 → JS动态为UL创建1个LI 为LI绑定一个Onlick事件。怎么做?

JS动态为UL创建1个LI 为LI绑定一个Onlick事件。怎么做?

时间:2011-11-23

来源:互联网

JS动态为UL创建1个LI 为LI绑定一个Onlick事件。怎么做?

作者: Unknownzh   发布时间: 2011-11-23

HTML code

<!doctype html>
<html>
    <head>
        <meta charset="gb2312" />
        <title></title>
        <style>
        </style>
        
    </head>
    <body>
        <ul id="test">
        </ul>
        <script>
            function $(o){return document.getElementById(o)}
            var li = document.createElement('li');
            li.innerHTML = 123;
            li.onclick = function(){
                alert(123)
            }
            $('test').insertBefore(li, $('test').firstChild)
        </script>
    </body>
</html>





作者: ootwo   发布时间: 2011-11-23

注意insertBefore的兼容性
用appendChild

作者: ifandui   发布时间: 2011-11-23

引用 2 楼 ifandui 的回复:
注意insertBefore的兼容性
用appendChild


up~`用 $('test').appendChild(li)

作者: MuBeiBei   发布时间: 2011-11-23

请说说在什么情况下 不兼容了?

我测试了的,ie ff下都没问题。

作者: ootwo   发布时间: 2011-11-23

该回复于2011-11-23 10:47:07被管理员删除

  • 对我有用[0]
  • 丢个板砖[0]
  • 引用
  • 举报
  • 管理
  • TOP
#6楼 得分:0回复于:2011-11-23 11:26:59
楼上已经有人给出正解,我只是来灌灌水 啊哈哈

作者: ootwo   发布时间: 2011-11-23

引用 4 楼 ootwo 的回复:
请说说在什么情况下 不兼容了?

我测试了的,ie ff下都没问题。


有人知道吗?

作者: acyexin   发布时间: 2011-11-23

用 JQuery 对li 标签添加Mousedown事件,xxx 表示li的class值,供参考

$(document).ready(function() {
  $("li.xxx").each(function() {
  if (!$.data(this, 'events') || $.data(this, 'events').mousedown === undefined) {
  $(this).mousedown(function() {
  //do something
  });
  }
  });

作者: ootwo   发布时间: 2011-11-24

$(function(){
  $("ul>li").bind({
  click:function(){
  if($(this).hasClass("red")){
  $(this).removeClass("red").addClass("blue");
  }else{
  $(this).removeClass("blue").addClass("red");
  }  
  }
  });
 });

动态给li绑定click事件,点击li进行class的red,blue变换,参考下吧

作者: wdhans   发布时间: 2011-11-24

都挺好,我就不帖代码了

作者: printf_2012   发布时间: 2011-11-24

相关阅读 更多