如果用户输入路径else返回空白,则返回分割值 [英] Return the split value if the user had entered the path else return blank
问题描述
我需要动态地显示用户输入的路径的名称和拆分路径。
为此,我拆分了用户输入的路径,只抓住了它的一部分。例如如果用户输入路径为:
I need to display the name and split path of the path entered by a user dynamically. For that, I had split the path entered by the user and grab only certain part of it. For e.g. if the user enters path as:
/content/mypath/myfolder/about/images/abc.jpg
然后我正在显示图像/ abc.jpg。
/content/mypath/myfolder/about/images/abc.jpg Then I am displaying images/abc.jpg.
但是,假设用户只输入名称,不会输入路径,至少应该使用该名称&在这种情况下显示。
However, let's say the user only enters the name and doesn't enter the path, at least the name should be applied & displayed in that case.
但是,每次输入路径时都会显示0。
我如何解决这个问题?
But it displays 0 everytime I enter a path. How do I fix this?
$(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>
推荐答案
应该解决你的问题。
我只更改了你的return语句 return newPath!= null? newPath:imgPath;
I've only changed your return statement 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
这篇关于如果用户输入路径else返回空白,则返回分割值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!