關於js開發的小問題

來源:互聯網
上載者:User

標籤:

一、開發當中經常會動態拼接html,當然為了簡便性好多人直接就是使用內聯事件:

$(‘#td1‘).html( ‘<a href="#" onclick="app.showPostEdit(‘+aData+‘)"></a>‘);
 $.Test = {            GetData: function () {                $.post("/Home/GetData", function (backdata) {                    var strHtml = "";                    $.each(backdata, function (itemIndex, item) {                        strHtml += "<div class=\"row\">";                        strHtml += "    <div class=\"col-md-4\">";                        strHtml += "        " + item.Id;                        strHtml += "    </div>";                        strHtml += "    <div class=\"col-md-4\">";                        strHtml += "        " + item.Url;                        strHtml += "    </div>";                        strHtml += "    <div class=\"col-md-4\">";                        strHtml += "        <button class=\"btn btn-sm\" onclick=\"$.Test.AppendBtn(" + item + ")\">" + item.Name + "</button>";                        strHtml += "    </div>";                        strHtml += "</div>";                    });                    $("#content").append(strHtml);                });            },            AppendBtn: function (str) {                console.log(str);                alert(str.Name);            }        };

瀏覽器會把它解析為:

<button class="btn btn-sm" onclick="$.Test.AppendBtn(eval([object Object]))">Name1</button>

毫無疑問,上面這種情況肯定是不對的;通常這種解決方案有兩種:

1、使用全域變數,函數中傳遞對象索引,在具體的函數根據索引取出相應的對象

2、不使用內聯事件,動態註冊事件

 

當然還有一種方法,就是把對象的屬性分別取出來進行傳遞;如果只有一兩個還可以,否則.........你懂的!如果有更好的解決方案,請指教,多謝哦!

 

二、當業務比較複雜,一個頁面中可能要寫多個js檔案,某個js檔案可能使用common.js中的方法,而真正去寫代碼時會發現沒有提示;

  只需要把common.js拖到你當前的js檔案中即可;

     你的js檔案會出現:/// <reference path="common.js" />

關於js開發的小問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.