jquery框架和mvvm框架的元素插入对比
这里的mvvm框架选用的是avalon.
元素插入用的是img做例子。
点击看效果demo
核心代码:
//jq way var picHref = $("<a></a>").attr("class","zxx_image_list"); var picSrc = $("<img</img>").attr("src",$img[count]).attr("class","zxx_image"); picHref.append(picSrc); picHref.appendTo($("#jqCover")); //vm way mvvmImg.imgArr.push($img[count]);
可以很清晰得看见。以上两种方式的效果是一样的,mvvm模式下的元素插入和删除会更加简洁。
demo源码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .demo-container{ width: 80%; margin: 0 auto; border-left: 1px solid #e4e4e4; border-right: 1px solid #e4e4e4; } .zxx_image_list{ display:inline-block; width:1.2em; margin-top:20px; text-align:center; font-size:128px; vertical-align:middle; } .zxx_image_list img.zxx_image{ padding:3px; width: 1.2em; height:0.72em; border:1px solid #828da1; background:white; vertical-align:middle; position:relative; } .zxx_image_list:hover,.zxx_image_list:hover .zxx_image{border-color:#ff3300;} .img-container{ padding-right: 252px; padding-left: 250px; } .finishedInfo{ text-align: center; display: none; } .title{ text-align: center; } </style> </head> <body> <div class="demo-container"> <button id="add">添加图片</button> <h4 class="finishedInfo">图片加载完成</h4> <div class="title"> jquery方式 </div> <div class="img-container" id="jqCover"> </div> <div class="title"> mvvm方式 </div> <div class="img-container" id="vmCover" :controller="pictureShow"> <a href="#" class="zxx_image_list" ms-for="(key,el) in @imgArr"> <img class="zxx_image" :attr="{src:@el}" /> </a> </div> </div> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script src="https://unpkg.com/avalon2@2.2.8/dist/avalon.js"></script> <script> let mvvmImg = avalon.define({ $id: 'pictureShow', imgArr: [] }); let $img = [ '../images/imgcommon1.jpg', '../images/imgcommon2.jpg', '../images/imgcommon3.jpg', '../images/imgcommon4.jpg', '../images/imgcommon5.jpg', '../images/imgcommon6.jpg', '../images/imgcommon1.jpg', '../images/imgcommon2.jpg', '../images/imgcommon3.jpg', '../images/imgcommon4.jpg', '../images/imgcommon5.jpg', '../images/imgcommon6.jpg', ]; let count = 0; var addImg = function(){ if(count >= $img.length){ $(".finishedInfo").css("display","block"); return; } else{ //jq way var picHref = $("<a></a>").attr("class","zxx_image_list"); var picSrc = $("<img></img>").attr("src",$img[count]).attr("class","zxx_image"); picHref.append(picSrc); picHref.appendTo($("#jqCover")); //vm way mvvmImg.imgArr.push($img[count]); count++; } }; $("#add").click(function(){ addImg(); }); </script> </body> </html>
夕阳下的奔跑,那是我逝去的青春