2017-04-21 42 views
0

我需要動態顯示用戶輸入的路徑的名稱和拆分路徑。 爲此,我分割了用戶輸入的路徑,並只抓取其中的一部分。對於例如如果用戶輸入路徑爲:如果用戶輸入了路徑,則返回拆分值否則返回空白

/content/mypath/myfolder/about/images/abc.jpg 然後我顯示圖像/ 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>

回答

1

這應該解決您的問題。

我只是改變了return語句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

謝謝你,但如果圖像路徑是空白的,它顯示0;理想情況下,它應該顯示空白。 – Sunny

+0

@Sunny立即嘗試。如果圖像路徑是黑色,則不會返回任何內容 –

+0

完美!謝謝! :) – Sunny

相關問題