问题
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 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.
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>
回答1:
This should solve your problem.
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
来源:https://stackoverflow.com/questions/43535696/return-the-split-value-if-the-user-had-entered-the-path-else-return-blank