将<div class =“span4”>与jQuery </div>中动态生成的按钮相关联

时间:2013-06-26 19:50:05

标签: jquery

<html>
    <head>
        <script type="text/javascript" src="file:///C:/jquery-1.7.1.min.js"></script>
        <script>
        $(document).ready(function(){
            var showGoals = $('<button>Show Globals</button>').click(function () { alert('hi')});
            var resp1 = $('<button>Show locals</button>').click(function () { alert('hi2')});

            $("#newId").append(showGoals, resp1);
            $("#newId").show();
        });
        </script>
    </head>
    <body>
        <div id="newId" style="display:none"></div>
    </body>
</html>

我希望按钮分别封装在div class =“span4”和div class =“span12”中。有人可以帮忙吗?我是jQuery的新手。

1 个答案:

答案 0 :(得分:1)

你可以这样做,例如:

var showGoals = $('<button>Show Globals</button>').click(function () { alert('hi')});

var showGoalsWrapper = $('<div class="span4"></div>');
showGoalsWrapper.append(showGoals);    

var resp1 = $('<button>Show locals</button>').click(function () { alert('hi2')});

var resp1Wrapper = $('<div class="span12"></div>');
resp1Wrapper.append(resp1);

$("#newId").append(showGoalsWrapper, resp1Wrapper);
$("#newId").show();