【发布时间】:2017-05-31 17:35:28
【问题描述】:
我们的任务是将给定的 svg 附加到 DIV 中,并在单击按钮 (.button-new) 时转换为内联 svg。
所以我们有一个具有特定宽度和高度的 div(#main-div),例如宽度和高度为 200 像素。
我们有一个宽度和高度为 50 px 的 svg。所以有total_no_blocks =4 元素进入容器。
我们编写以下代码将div 附加到svg 图像。
for(var i =0;i<total_no_blocks;i++){
$("#main-div").append("<img id=\"facebook-logo\" class=\"svg\" src=\""+img_src+"\" width=\"100\" />");
}
并转换为内联svg,我们使用以下代码
https://gist.github.com/Bloggerschmidt/61beeca2cce94a70c9df
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
问题是 javascript 不能一步一步工作。
根据我们的代码,前 4 张图片需要附加到 div 中,其次它转换为内联 svg。
但发生的情况是,在加载并向 main-div 显示 4 个图像之前的某个时间,它开始转换为内联 svg 。结果是第一次只加载了 2 个图像,同时加载了 3 个图像,或者有时它是正确的。
所以总的代码是这样的【这不是完整的代码】
$(".button-new").on("click",function(){
$("#main-div").children().remove();
for(var i =0;i<total_no_blocks;i++){
$("#main-div").append("<img id=\"facebook-logo\" class=\"svg\" src=\""+img_src+"\" width=\"100\" />");
}
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
function 3() etc.......
});
我知道 javascript 是同步的,但在某些情况下,比如 ajax,它会 一步一步的工作,因为它正在等待返回消息
。
当前情况下如何控制脚本的执行?
需要哪些步骤来确保所有步骤都在逐步执行并且所有执行都正确完成?
【问题讨论】:
-
AJAX代表Asynchronous Javascript And XML,是异步的...
标签: javascript jquery html svg