2015-08-15 59 views
-1

我有以下問題。jQuery插入到div後修改錨文本

我需要在div內添加dinamically後修改錨文本。

在我的代碼:

「加載文件」按鈕添加在div類=「格」(這是一個模擬)的文件中加載鏈接。 加載文件的程序無法修改。

該程序返回錨文本的路徑和文件名,但我只想保留名稱。

問題是,我沒有找到在哪個事件中放置我的代碼來修改錨文本。 我做了一個測試,它適用於mousemove事件,但只是一個測試。

如何觸發修改錨文本的代碼?

下面的代碼不起作用,但您可以嘗試啓用mousemove事件以查看所需的結果。

在此先感謝!您的幫助...

$(document).ready(function() { 
 
    $("#btnSave").click(function() { 
 
      // alert("Alert Click"); 
 
    \t $('.div').append(
 
      '<a id="link-x" href="http://example.com/file-3.pdf">http://example.com/file-3.pdf</a><br>'); 
 
\t }); 
 
    
 
/* This Works only for Testing 
 
    $(document).mousemove(function() { 
 
     $('a[id*="link"]').each(function(){ 
 
      var text = $(this).text(); 
 
      var html = $(this).html(); 
 
      var res = text .replace('http://example.com/', ''); 
 
      $(this).text(res); 
 
     }); 
 
\t }); 
 
*/  
 
    $('a[id*="link"]').on(function() { 
 
     $('a[id*="link"]').each(function(){ 
 
      var text = $(this).text(); 
 
      var html = $(this).html(); 
 
      var res = text .replace('http://example.com/', ''); 
 
      $(this).text(res); 
 
     }); 
 
\t }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div id="mycode"> 
 
<button id="btnSave">Load File</button> 
 
</div> 
 
<div class="div"> 
 
<a id="link-x" href="http://example.com/file-1.pdf">file-1.pdf</a><br> 
 
<a id="link-x" href="http://example.com/file-2.pdf">file-2.pdf</a><br> 
 
</div>

回答

0

試試這個:

$(document).ready(function() { 
    $("#btnSave").click(function() { 
     $('[id*="link"]').text(function() { 
      return $(this).text().replace("http://example.com/", ""); 
     }); 
    }); 
}); 

Fiddle

+0

嗨哥斯多, 感謝您的迴應, 按鈕上的代碼是一個模擬,該代碼不能被修改。 在reallity我不能訪問該代碼。 我得到的是需要改變的鏈接,以便任何人查看文件路徑。 – Memo

+0

@Memo所以現實中,點擊'#btnSave'後會出現鏈接嗎? –

+0

是單擊#btnSave後,鏈接出現,然後如何更改錨文本?這是可以捕捉的事件?動態代碼出現後。 – Memo