我試圖訪問一個元素的id,並切斷num以拼成ajax調用的url。我主要使用JQuery。需要一種方法從許多相同的元素之一獲取attr
我與.attr()和。數據()進行實驗,發現他們只返回了第一場比賽,所以每次它會1,不管我點擊了1,4或54
.get()只返回HTML標頭對象,我還沒有找到一種方法來訪問它,並可能拉出一個ID號。
代碼:
$('.display').click(function(event) {
event.preventDefault();
//get category from h4's parent div
let $parent = $('h4').parent();
let $cat = $parent.attr('class');
let cat = String($cat);
//get id to search for...currently only returning id_1, not unique id
let $id = $('h4').get(); //need correct method here
console.log($id);
//slice off num to use in ajax url req
if($id.length == 4) {
id_num = $id.slice(-1) + '/';
} else if ($id.length == 5) {
id_num = $id.slice(-2) + '/';
} else {
id_num = $id.slice(-3) + '/';
}
console.log(id_num);
$.ajax({
type: 'GET',
url: 'https://swapi.co/api/' + $cat + id_num,
success: function(result) {
console.log(result);
}
})
<div class="container">
<h3 id="title">I made the Kessel Run in 12 parsecs.</h3>
<form id ="searchParams" method="POST">
Now, I want to know about the
<input list="cats" name="cats">
<datalist id="cats">
<option id="people" value="people"></option>
<option id="planets" value="planets"></option>
<option id="films" value="films"></option>
<option id="species" value="species"></option>
<option id="vehicles" value="vehicles"></option>
<option id="starships" value="starships"></option>
</datalist>
in Star Wars.
<input id="getInfo" type="submit">
</form>
<div class="display"></div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/twelveparsecs.js"></script>
</body>
</html>
謝謝!
你試圖從哪個元素獲取id? – Flaugzig
'$(「input [list ='cats']」)。val()'會做什麼? (而不是當前的'.get()') – jrook
http://stackoverflow.com/questions/22110737/how-to-get-the-id-of-the-listitem-being-clicked-on-button-event 對於類似的問題感到抱歉,儘管措辭不佳。 – willwile4