【问题标题】:Display the split text of the path if it exists else display nothing如果存在,则显示路径的拆分文本,否则不显示
【发布时间】:2017-09-18 00:00:42
【问题描述】:

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

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

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

但是当我尝试这样做时会引发错误。

未捕获的类型错误:无法读取 null 的属性“0”

$(document).ready(function(){
  $('#getData').click(function(){
    var name = $('#name').val();
    var imgPath = $('#imgPath').val();
    var newPath = imgPath.match(/images\/.*$/i)[0];
    $('.container').append(
      $('<p>').text(name),
      $('<p>').text(newPath, function(){
        return /^\/images/.test(newPath) ? src :$('#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>

未捕获的类型错误:无法读取 null 的属性“0”

【问题讨论】:

    标签: jquery arrays dynamic split conditional-statements


    【解决方案1】:

    你的问题出在这一行

    var newPath = imgPath.match(/images\/.*$/i)[0];
    

    您正在尝试使用正则表达式运行匹配,然后选择第一个结果,即 [0] 位置。因此,当没有结果时,您尝试在没有结果时获取 [0] 位置。

    只需删除行尾的 [0] 即可

    var newPath = imgPath.match(/images\/.*$/i);
    

    【讨论】:

    • 完美,谢谢!顺便说一句,我在检查值的代码中使用 src 而不是 text 又犯了一个错误。
    • 很酷,你找到了它,告诉我是否可以提供其他帮助
    • 效果不错,但是我不认为我写的返回值是正确的!需要更改它以确保其正常工作!你能帮我做吗?
    • 你的问题已经解决了,我建议你创建一个新问题或者如果它很简单当然我可以尝试帮助,结果有什么问题?
    • 谢谢,我在这里找到了解决方案 - stackoverflow.com/questions/43535696/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2015-07-17
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多