美文网首页Web前端之路前端
如何利用jQuery封装一个简单的button组件

如何利用jQuery封装一个简单的button组件

作者: 张中华 | 来源:发表于2020-09-07 22:57 被阅读0次

前端开发组件化是一个趋势,也方便组件的复用。那么如何利用jQuery封装一个组件呢?就像jQuery UI那样,如何封装专属自己的UI组件呢?

文件目录:
index.html
index.js
index.css

index.js
class Button {
    static initial(selector, value) {
        $(selector).append(
            `
            <input class="jq-button" type="button" value="${value}"></input>
            `
        );

        $(`${selector} .jq-button`).click(function(e) {
            console.log(`${value} button is clicked`);
        });
    };

}
index.css
.jq-button{
    width: 80px;
    height: 40px;
    border-radius:10%;
    margin: 5px;
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="./index.js"></script>
    <link rel="stylesheet" href="./index.css" />
</head>
<body>
    <span class="button-test1"></span>
    <span class="button-test2"></span>
    <span class="button-test3"></span>
</body>
<script>
    Button.initial('.button-test1', 'Button1');
    Button.initial('.button-test2', 'Button2');
    Button.initial('.button-test3', 'Button3');
</script>
</html>
运行结果

利用这种方式封装组件,我们会发现一些问题,就是css样式是全局的,且需要添加一个没必要的标签<span class="button-test1"></span>,仅仅作为一个父标签,在其中添加内容而已。不过利用jQ封装组件貌似就是这样子的吧,不知道利用jQuery封装组件有没有更好的解决方案~

相关文章

网友评论

    本文标题:如何利用jQuery封装一个简单的button组件

    本文链接:https://www.haomeiwen.com/subject/llsrektx.html