只要只有一個選擇項,下面的代碼(在交互式代碼片段中)就能很好地工作,它讓我從json文件中選擇章節並在下面打印它們。使用select元素篩選多個json文件
我怎樣纔能有幾個來自兩個不同數組的元素? 當然,我必須將arr更改爲另一個變量名稱。 但是,如何指定我想要提供的選擇元素?
免責聲明:我得到了code from here和不完全理解它是如何工作
JavaScript和HTML
var arr = [{
"Content": ["<h2>Heading of Paragraph1</h2><p>the actual pargraph1</p>"],
"Titel": ["Heading of Paragraph1"]
},
{
"Content": ["<h2>Heading of Paragraph2</h2><p>the actual pargraph2</p>"],
"Titel": ["Heading of Paragraph2"]
}, {
"Content": ["<h2>Heading of Paragraph3</h2><p>the actual pargraph3</p>"],
"Titel": ["Heading of Paragraph3"]
}
];
//prepare the options first
var options = arr.map(function(item){
return "<option value='" + item.Titel[0] + "'>"+ item.Titel[0] + "</option>"
}).join("");
//set all the options to select and then bind change event
$("select").html(options).change(function(){
$("#paraContent").html("");
var val = $(this).val();
$("#paraContent").html(val.map(function(title){
return arr.find((s) => s.Titel[0] == title).Content[0];
}).join("</br>"))
//console.log(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/returnselected_paragraphs.js">
<select name="pargraphs" multiple>
</select>
<p id="paraContent">
</p>
<input type="submit">
</form>
這就是我試圖
https://jsfiddle.net/rba1amo7/
正如你所看到的,它加載第二個數據集到這兩個元素
我不能讓你通過怎樣的意思我能有幾個元素是從兩個不同的陣列?你是說你會有幾個數組,每個數組都將被分配給一個單獨的select元素,並且你需要將數組關聯起來進行選擇? –
我的意思是,'$(「select」)'顯然會選擇頁面上的所有選擇元素。如果你有多個,你只想在一個情況下改變一個,而另一個情況下你需要拋出一個類或一個id來識別和區分它們以查找$()。這有意義嗎? – Taplar
@MuhammadOmerAslam我基本上想要在一個頁面上使用相同的代碼,只是爲了不同的json文件。 – Nivatius