0

我不知道这个问题是否会被讨厌:s

我对 javascript 很陌生,想知道各位专家是否可以在下面看到任何明显的错误(糟糕的 javascript 编码)?或者有什么好的改进?

代码正在运行...

// add iframes to page
var normal_sortables = document.getElementById('normal-sortables');
normal_sortables.innerHTML = normal_sortables.innerHTML + '<div class="postbox"><iframe style="width:100%;height:300px;" id="iframe_upload" src="upload.php"></iframe><iframe style="width:100%;height:300px;" id="iframe_images" src="images.php"></iframe><iframe style="width:100%;height:300px;" id="iframe_pdf_documents" src="pdf.php"></iframe></div>';



// declaring all variables
var code_to_be_inserted = '',
textarea_content = document.getElementById('content'),
iframe_upload = document.getElementById('iframe_upload'),
iframe_images = document.getElementById('iframe_images'),
iframe_pdf_documents = document.getElementById('iframe_pdf_documents');



// upload iframes of images and pdf documents when file is uploaded
iframe_upload.onload = function () {
iframe_images.src = 'images.php';
iframe_pdf_documents.src = 'pdf.php';
}



// add image to content editor
iframe_images.onload = function () {
    var images = iframe_images.contentWindow.document.getElementsByTagName('img');
    for (var i = 0; i < images.length; i++) {
        images[i].onclick = function () {
            code_to_be_inserted = '<img alt="" src="'+this.src+'" />\n\n';
            textarea_content.value = code_to_be_inserted + textarea_content.value;
        }
    }
}



// add pdf documents to content editor
iframe_pdf_documents.onload = function () {
    var pdf_documents = iframe_pdf_documents.contentWindow.document.getElementsByTagName('a');
    for (var i = 0; i < pdf_documents.length; i++) {
        pdf_documents[i].onclick = function () {
            code_to_be_inserted = '\n\n<a href="' + this.href+'" target="_blank">Click here to open ' + this.innerHTML + '</a>';
            textarea_content.value = textarea_content.value + code_to_be_inserted;
            alert ('testar');
            return false;
        }
    }
}
4

1 回答 1

0

我会做这一项改进:

iframe_images.onload = function () {
    var pdf_documents = iframe_pdf_documents.contentWindow.document.getElementsByTagName('a');
    var total = pdf_documents.length;
    for (var i = 0; i < total; i++) {
        pdf_documents[i].onclick = function () {
            code_to_be_inserted = '\n\n<a href="' + this.href+'" target="_blank">Click here to open ' + this.innerHTML + '</a>';
            textarea_content.value = textarea_content.value + code_to_be_inserted;
            alert ('testar');
            return false;
        }
    }
}

这样你就不会在每次迭代时评估 pdf_documents.length 。如果该长度很短,这不会损害您的性能,但是如果您正在浏览大量列表,您肯定会希望首先定义总数而不是在循环中。

于 2011-12-16T01:46:38.420 回答