最近也是在做项目的时候刚接触到jQuery。下面汇总一下遇到的几个问题

   方式一: $("#a").html("<input type='button' value='按钮'  class='button‘/>");

   方式二: $("#a").append("<input type='button' value='按钮' class='button‘/>");

<input  type="button" />
<input  type="button" />


<div >
    <p>添加一个按钮的地方:</p>
</div>

<script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>

<script type="text/javascript">
    $(function () {
        $("#add_html").click(function () {
            $("#a").html("<input type='button' value='按钮' class='button'/>");
        })

        $("#add_append").click(function(){
            $("#a").append("<input type='button' value='按钮' class='button'/>");
        })        
    })
</script>

两种做法得到的效果是:

      html只会在标签处生成相应的按钮,即不管点几下,都只生成一个按钮
Jquery中常见问题

 

      append是在标签的最后添加,点一次,就会出现一个按钮

Jquery中常见问题

      还有一种方法是

1 $("#add").click(function () {
2             $("<input type='button' value='新按钮' class='button'/>").insertAfter("#a");
3             $("<input type='button' value='新按钮' class='button'/>").insertBefore("#a");
4         })

 

  • 如何对动态添加的按钮绑定事件

    上面所讲的生成的按钮就是动态按钮(由脚本创建的新元素),我们通常使用的click事件

     $('.button').click(function(){});

    只能绑定到页面中当前存在的对象,而对于动态生成的对象不能绑定

    这里就用到两种方法 :    on()方法或者deletege()方法

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


<input  type="button" />

<div > 
    <input type="button" class="button" value="按钮"/>
    <div >
        <p>添加一个按钮的地方:</p>
    </div>
</div>

<script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $("#add_append").click(function () {
            $("#a").append("<input type='button' value='新按钮' class='button'/>");
        })

        //以下两种方法都可以实现
        //添加元素必须是某一个元素的子元素

        //$("#abc").on("click", ".button", function () {
        //    alert("1");
        //})

        $("#abc").delegate(".button", "click", function () {
            alert("1");
        })
    })
</script>

 

  • 元素的定位

  •  children()只能向下遍历一级(子元素); find()可以找出所有后代元素
  •  $("tr td") tr的所有后代元素td;  $("tr>td") tr的子元素td
  •  parent 父元素; cloest 最近的祖先元素
  •  按层次查找元素 $("#a b c d") 每一层次所在的元素个数必须是一个(each方法的最后一个除外)

 

  • 方法定义相关

    1. 定义数组

     var aArray={}

     使用的时候  aArray[i]

 var aArray = {};
    var i = 0;
    $.each($("#"+TableId+" > tbody >tr"), function (index, item) {
        if ($(this).children("td").first().find("input").attr("checked") == 'checked') {         
            aArray[i] = $(this).children("td").last().find("input").val();            
            i++;
        }
    });
View Code

相关文章:

  • 2021-08-23
  • 2022-02-09
  • 2021-12-19
  • 2021-05-31
  • 2021-05-26
  • 2022-12-23
  • 2022-12-23
  • 2022-01-18
猜你喜欢
  • 2021-08-31
  • 2022-12-23
  • 2022-01-01
  • 2021-09-25
  • 2021-10-25
  • 2022-03-05
  • 2022-12-23
相关资源
相似解决方案