js动态追加的元素如何触发事件

一般通过js或者jQuery动态添加的元素标签,通过该元素标签、class、id触发事件,是无效的。如下所示:

<body>
<input type="text" class="ceshi" />
<input type="text" class="ceshi" />
<input type="text" class="ceshi" />
<button onclick="addLine();">点击添加</button>

<script>
    function addLine() {
        var html = "<input type='text' class='ceshi' />";
        $('.ceshi:last').after(html);
    }
    $(".ceshi").on('focus', function () {
        $(this).val(111);
    });
</script>
</body>

 

在既有的<input>后面再通过按钮点击事件,在js中动态添加一个<input>元素,我们通过页面操作可以发现,既有的元素聚焦后输入框内会添加“111”,而js添加的第四个输入框元素,聚焦后并不会触发focus事件。如图所示:

如果想要触发新标签的事件,解决方法有两种:

(1)在标签内添加事件触发方法,例如:<a onclick="test();"></a>

<body>
<input type="text" class="ceshi" onfocus="test(this);"/>
<input type="text" class="ceshi" onfocus="test(this);"/>
<input type="text" class="ceshi" onfocus="test(this);"/>
<button onclick="addLine();">点击添加</button>

<script>
function addLine() {
var html = "<input type='text' class='ceshi' onfocus='test(this);'/>";
$('.ceshi:last').after(html);
}

function test(param) {
$(param).val(111);
}
//$(".ceshi").on('focus', function () {
// $(this).val(111);
//});
</script>
</body>

 

 效果如图所示,聚焦到第四个动态添加的输入框时,可触发聚焦事件。

 

(2)调用jQuery的delegate函数,delegate函数可以根据特定的根元素,把一个或者多个事件注册到指定的元素上,不论这个元素现在是否存在。

<body>
<input type="text" class="ceshi"/>
<input type="text" class="ceshi"/>
<input type="text" class="ceshi"/>
<button onclick="addLine();">点击添加</button>

<script>
    function addLine() {
        var html = "<input type='text' class='ceshi'/>";
        $('.ceshi:last').after(html);
    }
    $(function () {
        $("body").delegate("input",
            "focus",
            function () {
                $(this).val(111);
            });
    });

    //function test(param) {
    //    $(param).val(111);
    //}

    //$(".ceshi").on('focus', function () {
    //    $(this).val(111);
    //});
</script>
</body>

 

效果图和方法(1)是一致,不再赘现。

使用此方法时,如果需要多次变更绑定的事件,需要先解除绑定后才能再次绑定事件,解除绑定的方法:

$("body").undelegate();

 

以上就是两种解决动态添加标签的事件绑定方法啦,感谢阅读!

 /******************************我是可爱的分割线**********************************/

 

posted @ 2018-11-06 14:02  Merryan  阅读(6494)  评论(0编辑  收藏  举报