2012-11-28 36 views
0

我有一個示例代碼:從javascript中事件onclick獲取值時出錯?

<span id="app_name_1"></span><a onclick="addSelectApplication('name 1');" href="#">Add name 1</a>     
<span id="app_name_2"></span><a onclick="addSelectApplication('name 2');" href="#">Add name 2</a>    
<span id="app_name_3"></span><a onclick="addSelectApplication('name 3');" href="#">Add name 3</a> 

和JavaScript

<script> 
function addSelectApplication(title) { 
    for(var i=0; i<3; i++) { 
     parent.document.getElementById('app_name_'+i).innerHTML = title; 
    }  
} 
</script> 

當我點擊Add name 1,結果是

<span id="app_name_1">name 1</span> 
<span id="app_name_2">name 1</span> 
<span id="app_name_3">name 1</span> 

如何使用結果的解決方法是:

當點擊Add name 1

<span id="app_name_1">name 1</span> 
<span id="app_name_2"></span> 
<span id="app_name_3"></span> 

當單擊Add name 2

<span id="app_name_1"></span> 
<span id="app_name_2">name 2</span> 
<span id="app_name_3"></span> 
+0

爲什麼使用家長?這是在iframe或其他內容 –

+0

這些答案中的任何一個解決您的問題?如果是這樣,請接受你最感到幫助的人。 – Madbreaks

回答

2

你遍歷所有的跨度和設置標題。你需要以某種方式確定你點擊其中一個,這裏從標題本身:

function addSelectApplication(title) { 
    // Extract the link clicked from the title text 
    var i = title.replace(/.*(\d)/, "$1"); 

    // Set the content 
    parent.document.getElementById('app_name_'+i).innerHTML = title; 
} 

乾杯

0

試試這個

function addSelectApplication(title) 
    { 
     var splitStr = title.split(' '); 

     for (var i = 1; i < 4; i++) 
     { 
      if (splitStr[1] == i.toString()) 
      { 
       parent.document.getElementById('app_name_' + i).innerHTML = title; 
      } 
      else 
      { 
       parent.document.getElementById('app_name_' + i).innerHTML = ""; 
      } 
     } 
    } 
0

對於當前的HTML格式,最簡單的方法是:

<span id="app_name_1"></span><a onclick="this.previousSibling.innerHTML = 'name 1';" href="#">Add name 1</a>    
    <br /> 
    <span id="app_name_2"></span><a onclick="this.previousSibling.innerHTML = 'name 2';" href="#">Add name 2</a>    
    <br /> 
    <span id="app_name_3"></span><a onclick="this.previousSibling.innerHTML = 'name 3';" href="#">Add name 3</a> 
0
<span id="app_name_1"></span> 
<span id="app_name_2"></span> 
<span id="app_name_3"></span> 

<a title="name 1" onclick="addSelectApplication(this);" href="#">Add name 1</a>    
<a title="name 2" onclick="addSelectApplication(this);" href="#">Add name 2</a>    
<a title="name 3" onclick="addSelectApplication(this);" href="#">Add name 3</a> 
<script> 
    function addSelectApplication(obj) {  
    for(var i=1; i<=3; i++) {   
     var no = obj.title.split(' '); 
     if (no[1] == i) { 
      document.getElementById('app_name_'+i).innerHTML = obj.title;  
     } else { 
      document.getElementById('app_name_'+i).innerHTML = '';  
     } 
    } 
    return false;  
} 
</script>