2015-02-24 47 views
0

我需要找到一種方法將正確的輸入傳遞給此javascript函數,以使其搜索XML文檔並返回請求的節點值。 XML節點值的分析實際上並正常工作時,硬編碼,如下圖所示,我可以用成功加載內容如下:Jquery onclick事件加載XML的特定節點

function parse(document){ 

    Lyrics2 = $(document).find('elementRef[id="2"] content').text() 
    Ref2 = $(document).find('elementRef[id="2"] bibleRefs').text() 
    $("#content").text(Lyrics2); 
    $("#scripture").text(Ref2); 
    }; 

$.ajax({ 
url: 'songlyrics.xml', 
dataType: "xml", 
success: parse 
}); 

的問題是我想傳遞給解析功能的附加參數在XML中搜索其他內容。最終的目標是擁有一個div更新與從XML文檔修改的內容在頁面上一旦鏈接被點擊,例如,像這樣(其中「基準」是通過在搜索字符串):

function parse(document,reference){ 

    Lyrics2 = $(document).find(reference).text() 
    $("#content").text(Lyrics2);  
}; 

... 
<div id="content"></div> 
<a href="javascript:;" id="play" onclick="javascript:parse(document,'elementRef[id=\&quot;2\&quot;] artist')">Title</a> 

正在發生的事情是,點擊一個指定了運行'parse'函數的鏈接後,頁面加載中出現的文本被替換爲空白 - 在調試窗口中不會生成錯誤。

XML:

<?xml version="1.0" encoding="UTF-8"?> 
     <elements> 
      <elementRef id="1"> 
       <name>John</name> 
       <artist>Smith</artist> 
       <content>Active</content> 
       <supportImg>test1</supportImg> 
       <bibleRefs>Mark 2:13</bibleRefs> 
       <other>Mark 2:11</other> 
      </elementRef> 
      <elementRef id="2"> 
       <name>Jane</name> 
       <artist>Smith</artist> 
       <content>Active</content> 
       <supportImg>test2</supportImg> 
       <bibleRefs>John 3:17 Mark 12:3</bibleRefs> 
       <other>October, 2011</other> 
      </elementRef> 
</elements> 

請讓我知道如果你爲了幫助需要更多的信息。任何幫助是極大的讚賞。

回答

0

我想你在找什麼是

function parse(reference) { 
    if (!xml) { //the ajax request is not yet loaded so there is nothing to do 
     return; 
    } 
    var content = $(xml).find(reference).text() 
    $("#content").text(content); 
}; 

var xml; 
$.ajax({ 
    url: ' 
    songlyrics.xml ', 
    dataType: "xml", 
    success: function (doc) { 
     //assign the loaded xml content to a gloabl variable so that it can be used later 
     xml = doc; 
    } 
}); 

然後

<a href="javascript:;" id="play" onclick="javascript:parse('elementRef[id=\&quot;2\&quot;] artist')">Title</a> 
+0

謝謝,當我回家,我會試試這個!真的很感激阿倫! – 2015-02-24 16:01:51