【问题标题】:Step by step execution of javascript or Jquery in specific condition在特定条件下逐步执行 javascript 或 Jquery
【发布时间】: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


【解决方案1】:

让我们总结一下场景:

  • 用户点击.button-new按钮
  • 元素#main-div 将附加total_no_blocks facebook 徽标的数量,即img.svg
  • img.svg 项目被迭代
  • 向服务器发送 AJAX 请求以获取图片(在每次迭代中)
  • 响应被解释为 SVG 并写入而不是带有 id 的标签

主要问题是您的代码假定正在等待 facebook 徽标。这不是它的工作方式。事实上,标签是立即创建的,随后的迭代发生在标签创建之后,但是这些是从某处加载的图像(除非缓存),而且是异步的。您需要实现 $("#main-div &gt; img").load() 处理程序并将替换图像的逻辑放在那里。这将等待特定标签被加载并做需要做的事情。但是,您还有其他问题。您的id 在每种情况下都是facebook-logo,这违背了ids 的目的,即识别标签。因此,您也需要在周期中进行此更改:

$("#main-div").append("<img id=\"facebook-logo" + i + "\" class=\"svg\"  src=\""+img_src+"\" width=\"100\" />");

这将使项目独一无二。最后,我不明白你为什么要生成没有任何目的的图像,因此会被 svg 图像覆盖。如果这具有教育或说明目的,那么您可能需要考虑将您的 $("#main-div &gt; img").load() 处理程序包装到 setTimeout 中,等待一秒钟,例如让人眼看到初始图像是什么。如果没有,那么你可以简单地从一开始就使用 svg 来避免所有的麻烦。

【讨论】:

  • @abilasher 欢迎您,祝您在项目中一切顺利。
  • 您能总结一下整个代码的情况吗?同样在这里我没有使用 Ajax。但是为什么你说 AJAX 请求被发送到服务器以获取图片?
  • @abilasher 第一个问题的答案是肯定的,但我需要你提供一个小提琴来测试代码,以确保一切正常,没有错别字等等。第二个问题的答案是服务器有一个异步请求来获取文件,并且这个请求没有等待完成。因此这是异步的。浏览器的内部逻辑是否涉及到Javascript和XML其实我不知道,在某些浏览器中可能是这样,但它的工作方式与AJAX非常相似。
  • @abilasher 所以,也许我有点夸张了。我真正的意思是它是一个异步请求,当文件被成功提取时,您可以为该事件附加一个事件处理程序。这个处理程序与 AJAX 请求的回调非常相似。
  • @abilasher 我对截屏没有太多经验。
【解决方案2】:

这是一个小示例,您可以从中了解发生了什么。将一个简单的回调作为函数的参数。

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>SVG 001</title>
    <style>
      body{font-family:"Calibri", sans-serif;}
      svg{border:1px solid #eee;float:left;}
    </style>
  </head>
    <body>
      <h1>Offset Dasharray</h1>
      <svg width="200" height="200" viewBox="0 0 500 500">
        <path id="myPath" d="M 50 50 q 200 800 400 0" stroke="none"stroke-width="5" fill="none" />
      </svg> 
      <p id="astart"><p>
      <p id="aend"><p>
      <p id="acallback"><p>
      
      <script>
        var paintPathAni=function(path, duration, color, callback){
          easeInOutQuad= function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t }
          var len=path.getTotalLength();  
          var aktLen;
          var sumSteps = duration / (1000/60) // 60 pics per second
          var step=1;
          var pathAnim;
          var anim=function(){
            aktLen = easeInOutQuad(step/sumSteps)*len; 
            path.setAttribute('stroke-dasharray', aktLen + ' ' + (len - aktLen));
            path.setAttribute('stroke',color);
            if (step < sumSteps){
              step++;
              pathAnim = setTimeout(anim, 1000/60) //1000/60 pics/second
              } else {
                clearTimeout(pathAnim);
                path.setAttribute('stroke',"red");
                path.setAttribute('stroke-dasharray','none');
                if (callback) return callback();
              }
          }
          anim();   
      }
      astart.innerHTML="before function call";
      paintPathAni(myPath, 5000,'red',function(){acallback.innerHTML="callback call";});
      aend.innerHTML="after function call";
    </script>
  </body>  
  </html>  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-10
    • 2022-10-19
    • 2019-12-17
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    相关资源
    最近更新 更多