【问题标题】:Return the split value if the user had entered the path else return blank如果用户输入了路径,则返回拆分值,否则返回空白
【发布时间】:2017-09-18 01:00:57
【问题描述】:

我需要动态显示用户输入的路径的名称和分割路径。 为此,我拆分了用户输入的路径并仅抓取其中的一部分。例如如果用户输入路径为:

/content/mypath/myfolder/about/images/abc.jpg 然后我正在显示 images/abc.jpg。

但是,假设用户只输入名称而不输入路径,至少在这种情况下应该应用并显示名称。

但每次我输入路径时它都会显示 0。 我该如何解决这个问题?

$(document).ready(function(){
  $('#getData').click(function(){
    var name = $('#name').val();
    var imgPath = $('#imgPath').val();
    var newPath = imgPath.match(/images\/.*$/i);
    $('.container').append(
      $('<p>').text(name),
      $('<p>').text(function(imgPath){
        return newPath ? imgPath : $('#imgPath').val();
      })
    );
    //console.log(slicedPath);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
Name: <input type="text" id="name">
Image path: <input type="text" id="imgPath">
<div class="container">

</div>
<button id="getData">Click</button>

【问题讨论】:

    标签: jquery dynamic split return conditional-statements


    【解决方案1】:

    这应该可以解决您的问题。

    我只是更改了您的退货声明return newPath != null ? newPath : imgPath;

    $(document).ready(function(){
      $('#getData').click(function(){
        var name = $('#name').val();
        var imgPath = $('#imgPath').val();
        var newPath = imgPath.match(/images\/.*$/i);
        $('.container').append(
          $('<p>').text(name),
          $('<p>').text(function(imgPath){
            return newPath != null ? newPath : $('#imgPath').val();
          })
        );
        //console.log(slicedPath);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    Name: <input type="text" id="name">
    Image path: <input type="text" id="imgPath">
    <div class="container">
    
    </div>
    <button id="getData">Click</button>
    
    
    /content/mypath/myfolder/about/images/abc.jpg

    【讨论】:

    • 谢谢,如果图片路径为空,则显示为0;理想情况下,它应该显示为空白。
    • @Sunny 立即尝试。如果图像路径为黑色,则不返回任何内容
    • 完美!谢谢! :)
    • 我在 JSON 的情况下问过一个类似的问题,如何让它工作。你能帮我解决这个问题吗? stackoverflow.com/questions/43537688/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2020-08-09
    • 2022-10-12
    相关资源
    最近更新 更多