在 JavaScript 中獲取 XML 資料中的任意屬性值?


若要從 XML 資料獲取任意屬性的值,請在 JavaScript 中使用 attr()。以下是程式碼 −

示例

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<script>
   var yourXMLDetails = '<Game id="101" details="Play the game and win the amount">'
   +'<gameName name="Cricket" content="/localhost/content/game/play/" />'
   +'<gameName name="Tennis" content="/localhost/game/all/scratch/" />'
   +'</Game>'
   console.log("Game Details==="+$(yourXMLDetails).attr("details"));
</script>
</body>
</html>

要執行上述程式,請儲存檔名“anyName.html(index.html)”並右鍵單擊該檔案。在 VS Code 編輯器中選擇“用 Live Server 開啟”選項。

輸出

這將生成以下輸出 −


更新於:07-Sep-2020

1K+ 瀏覽量

開啟您的 職業

完成課程獲得認證

開始
廣告