jQuery可以操作插入的元素吗? [英] Can jQuery manipulate inserted elements?

查看:93
本文介绍了jQuery可以操作插入的元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jQuery的新手。我认为jQuery可以操纵代码添加的元素是合理的,但我发现它现在不能。

I'm a freshman to jQuery. I think it's reasonable that jQuery could manipulate elements added by code, but I found it couldn't just now.

$(function(){
    $("#addVideo").click(function(){
         $("#publisher").append("<div id='choseType'><input type='button' value='video'> <input value='music' type='button'> <input type='button' value='X'></div>");
    })      
    $("#choseType input:eq(0)").click(function(){
     $(this).addClass("selected");
    })
})

是jquery的限制还是我的代码的错?看来如果我将第二个 click()函数放入第一个正确运行的函数中,但它只会运行一次(如果我删除附加的 #choseType 并再次附加它,第二次点击将无效。)。那么我如何操作代码添加元素?谢谢!

Is it jquery's limitation or my code's fault? It seems if I put the second click() function into the first one it will run correctly, but it will only run once(if I remove the appended #choseTypeand append it again the second click won't work.).Then how do I manipulate code added elements? Thanks!

推荐答案

$(function(){
    $("#addVideo").click(function(){

        //create new content, and append to publisher
        //also, reference the new content
        var newContent = $("<div><input type='button' value='video'> <input value='music' type='button'> <input type='button' value='X'></div>").appendTo('#publisher');

        //then add a handler to input in the context of the new content
        $("input:eq(0)", newContent).click(function(){
            $(this).addClass("selected");
        });
    })    
})

这篇关于jQuery可以操作插入的元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆