2015-07-03 51 views
0

我需要更改span類標記的類別u的內容,當某人點擊p標記時,它們各自的id標記將作爲參數傳遞給函數,以便函數可以轉換將該數字轉換爲數字,並訪問數組中的數值,並將該數字作爲新值添加,完全替換之前的值。jquery從點擊數組中更改跨度標記內容

//html code 
    <span id="u">My point</span> 
    <p class="current" id="one" onclick="chan('one')">My point</p> 
    <p id="two" onclick="chan('two')">text2</p> 
    <p id="three" onclick="chan('three')">text2</p> 
    <p id="four" onclick="chan('four')">text2</p> 
    <p id="five" onclick="chan('five')">text2</p> 
    <p id="six" onclick="chan('six')">text2</p> 
    <p id="seven" onclick="chan('seven')" >text2</p> 



//javascript code 

    var titl = ['My point', 
       'text2', 
       'text3', 
       'text4', 
       'text5', 
       'text6', 
       'text7' 
       ]; 

    function chan(pin){ 
     if(pin="two"){ 
       it = 1; 
       } 
       else if(pin="one"){ 
       it = 0; 
       } 
       else if(pin="three"){ 
       it = 2; 
       } 
       else if(pin="four"){ 
       it = 3; 
       } 
       else if(pin="five"){ 
       it = 4; 
       } 
       else if(pin="six"){ 
       it = 5; 
       } 
       else if(pin="seven"){ 
       it = 6; 
       } 

       document.getElementById("u").innerHTML = titl[it; 
    } 

回答

0

試試這個:

<p class='js-load-number' data-number='0'>one</p> 
<p class='js-load-number' data-number='2'>three</p> 
<p class='js-load-number' data-number='3'>four</p> 

而jQuery的:

var updateScore = function() { 
    var numberFromClicked = $(this).data('number'); 
    $('#u').html(numberFromClicked); 
} 
$('.js-load-number').click(updateScore); 

這個lea你會用更清潔的代碼來工作,並且在將來對你很好。

我已經從HTML中刪除了onclick屬性,並使用jquery的.click()方法,該方法將預定義的函數作爲參數。單獨的功能更清晰,更可重用。

我將HTML數據定義爲數據屬性,這是將數據存儲在HTML中的更好方法。它使用jquerys data()方法訪問。你可以把任何你喜歡的數字放在data屬性中,這樣就不需要javascript中的轉換數組了。

我們還用$(this)結構jQuery中提及觸發事件的元素(在這種情況下,單擊事件)

+1

謝謝.. !!!有效 – xxCodexx

0

有錯誤的class和id爲U,在JavaScript代碼也有一些錯誤:我有變化的代碼

//html code 
    <span class="u" id="u">My point</span> 
    <p class="current" id="one" onclick="chan('one')">My point</p> 
    <p id="two" onclick="chan('two')">text2</p> 
    <p id="three" onclick="chan('three')">text2</p> 
    <p id="four" onclick="chan('four')">text2</p> 
    <p id="five" onclick="chan('five')">text2</p> 
    <p id="six" onclick="chan('six')">text2</p> 
    <p id="seven" onclick="chan('seven')" >text2</p> 



//javascript code 

    var titl = ['My point', 
       'text2', 
       'text3', 
       'text4', 
       'text5', 
       'text6', 
       'text7' 
       ]; 

    function chan(pin){ 
     if(pin="two"){ 
       it = 1; 
       } 
       else if(pin="one"){ 
       it = 0; 
       } 
       else if(pin="three"){ 
       it = 2; 
       } 
       else if(pin="four"){ 
       it = 3; 
       } 
       else if(pin="five"){ 
       it = 4; 
       } 
       else if(pin="six"){ 
       it = 5; 
       } 
       else if(pin="seven"){ 
       it = 6; 
       } 

       document.getElementById("u").innerHTML = titl[it]; 
    } 
+0

什麼是JavaScript的部分錯誤 – xxCodexx