简体   繁体   English

如何在li中动态获取动态创建的ID

[英]How to dynamically get the dynamically created ID in a li

I've been trying to learn js (and a tad of jquery) and I have run into two difficulties when trying to find a way to combine solutions that I find. 我一直在尝试学习js(以及一堆jquery),并且在尝试找到一种结合我发现的解决方案的方法时遇到了两个困难。

Just a little warning that this code is a mix of a few tutorials that I have recently done. 只是一点警告,此代码是我最近完成的一些教程的混合。 I am very new to js. 我对js很陌生。

So I start with a basic html with a few li. 因此,我从基本的html开始。

<body>  
<ol id="liste">
<li class="active">   
</li>
<li>      
</li>
<li>
</li>   
</ol>
<div id="main_ima">



</div>
<script src="js/main.js"></script>
</body> 

I want to create ids for each "li" so in my main.js I add this: 我想为每个“ li”创建id,因此在main.js中添加以下代码:

var idVar = $("#liste").find("li").each(function(index){
$(this).attr("id","num-li-"+index);
});

This works great so far. 到目前为止效果很好。 Everytime I add a new li, it gets a new id. 每当我添加一个新的li时,它都会得到一个新的id。 I also put it into a var because I will need to use it later. 我也将其放入var中,因为以后需要使用它。

In th console, If I type idVar, it gives me the whole list of li. 在控制台中,如果输入idVar,它将显示li的整个列表。 If I type idVar[3]. 如果我输入idVar [3]。 it only gives me the li associated to the [3]. 它只给了我与[3]关联的li。 Perfect. 完善。

Now I want to get something to appear when one of the li is clicked. 现在,当单击li之一时,我想让某些东西出现。 For example, I will use the [3]. 例如,我将使用[3]。 So I add this to my main.js 所以我将此添加到我的main.js

var imaContainer = document.getElementById('main_ima')
var listed = document.getElementById('liste');



idVar[3].addEventListener("click", appar); 


function appar(){

$(idVar[3]).addClass("active").siblings().removeClass("active");



var imaSel = new XMLHttpRequest();

imaSel.open('GET', 'https://domain.link.to.file.json');
imaSel.onload = function() {

var imaLo = JSON.parse(imaSel.responseText);
renderHTML(imaLo); 
};
imaSel.send();


};


function renderHTML(data) {
  var htmlS = "";

for (i = 0; i < data.length; i++) {
                           htmlS += "<p>" + data[i].name + " is a " + data[i].species + ".</p>";                           

}                              


imaContainer.insertAdjacentHTML('beforeend', htmlS);

}

Just a side note, I added the add/remove "active" class for CSS. 只是附带说明,我为CSS添加了添加/删除“活动”类。

So when I click the li[3], it works almost as expected. 因此,当我单击li [3]时,它几乎可以按预期工作。 The only thing is when I reclick [3] it produces the result a 2nd time. 唯一的事情是,当我重新单击[3]时,它将第二次产生结果。 And again, if I click it a 3rd time, it produces the result a 3rd time, without remove the past results. 再一次,如果我第三次单击它,它将第三次产生结果,而不会删除过去的结果。 (which is not totally what I want. Just the 1st result would be better.) (这不完全是我想要的。只是第一个结果会更好。)

But that is not the main problem I am facing. 但这不是我面临的主要问题。

I would like the [number] to be dynamically detected, based on the id of the clicked li. 我希望根据单击的li的ID动态检测[number]。 I could, in a very ugly way, copy and past this code for every [number] I have. 我可以以非常难看的方式为我拥有的每个[数字]复制并粘贴此代码。 and it would work. 它会工作。 But then, what if I want to add more li elements, I would need to add more copy and paste of the above code, giving me possibly huge files for nothing. 但是,如果我想添加更多li元素,我将需要添加上述代码的更多副本和粘贴,这可能给我带来巨大的文件负担而已。 This is surely not the best way, although it would work. 虽然可以,但这肯定不是最好的方法。

I'm sure this can be done dynamically.. but that is mostly why I am here. 我敢肯定这可以动态完成。但这就是为什么我在这里。 :) :)

Afterwards, once the dynamic has been added to the clicked li, I would also like the link to be changed dynamically based on the li id. 之后,将动态添加到单击的li后,我还希望根据li id动态更改链接。 For example, instead of : 例如,代替:

imaSel.open('GET', 'https://domain.link.to.file.json');

something like: 就像是:

imaSel.open('GET', "https://domain.link.to.file" + var +".json");

the var being equal to the [3] number of the clicked li. var等于单击的li的[3]号。

In this case, when I try to add a var with a for loop, I always get the "var = max.length" instead of the "var = [id of clicked item]". 在这种情况下,当我尝试使用for循环添加var时,总是得到“ var = max.length”而不是“ var = [clicked itemid]”。

So there you have it. 所以你有它。 Do you need more details? 您需要更多详细信息吗?

This is my first JS and/or Jquery try. 这是我第一次尝试JS和/或Jquery。 I've been playing with it for a few days but when I search for answers, when I implement the "solutions" it alwas gives me some new problem. 我已经玩了几天,但是当我寻找答案时,当我实现“解决方案”时,总是给我带来一些新问题。 So I am showing you the code that is the closest, IMO, to what I am looking for. 因此,我向您展示了与我正在寻找的代码最接近的IMO。

Hopefully, I am not too far away of somehting that works and is not as big as my solutions. 希望我离可行的事情不太远,并且不如我的解决方案那么大。 :) :)

Thanks for your time and all help is appreciated. 感谢您的宝贵时间,我们将为您提供所有帮助。

Here are some suggestions: 这里有一些建议:

  • You don't need to assign id attributes to your li . 您无需为li分配id属性。 You actually never need that id . 实际上,您永远不需要该id This will work just as well (note also the > in the selector which makes the find call unnecessary): 这也将正常工作(请注意选择器中的> ,这将使find调用变得不必要):

     var $li = $("#liste > li"); 

    Already now you can address each of the li as $li[3] , although that is not the "best practise". 现在,您可以将每个li称为$li[3] ,尽管那不是“最佳实践”。 Better is $li.get(3) . 更好的是$li.get(3) I also like the convention to start the variable with $ when it is the result of a jQuery selection. 我也喜欢约定,当它是jQuery选择的结果时,以$开头变量。 It gives a clue that you can apply jQuery methods to it. 它提供了一个提示,您可以将jQuery方法应用于该提示。

  • You don't need to assign a click handler to each li separately. 您无需为每个li单独分配一个点击处理程序。 With jQuery on (instead of the native addEventListener ) you can assign one event handler for all of them at once. 与jQuery on (而不是原生addEventListener ),你可以一次给所有他们中的一个事件处理程序。

     $li.on('click', apar) 
  • The callback you define for on will have this set to the particular li element that has been clicked, so you can do: 您为on定义的回调会将this设置为已单击的特定li元素,因此您可以执行以下操作:

     $(this).addClass("active").siblings().removeClass("active"); 

    ... without any array lookup. ...无需任何数组查找。

  • jQuery offers easy functions for several types of HTTP requests, so you don't need to use XMLHttpRequest . jQuery为几种类型的HTTP请求提供了简单的功能,因此您无需使用XMLHttpRequest In fact, there is one specifically for getting JSON, so you don't even have to parse the response: 实际上,有一个专门用于获取JSON的代码,因此您甚至不必解析响应:

     $.getJSON('https://domain.link.to.file.json', renderHTML); 
  • The jQuery index() method can give you the sequence number of that li : jQuery index()方法可以为您提供li的序列号:

     $.getJSON('https://domain.link.to.file' + $(this).index() + '.json', renderHTML); 
  • To replace the inner HTML of a certain element, the jQuery html method can be used: 要替换某个元素的内部HTML,可以使用jQuery html方法:

     $('#main_ima').html(htmlS); 

    Note also how you don't need the DOM native getElementById method, jQuery can look that up for you with the short $('#main_ima') . 还要注意,您不需要DOM本机的getElementById方法,jQuery可以使用简短的$('#main_ima')为您查找。

Example

Here is a working example with a fake JSON serving server: 这是一个使用伪造的JSON服务服务器的工作示例:

 $("#liste > li").on('click', apar); function apar() { $(this).addClass("active").siblings().removeClass("active"); $.getJSON('https://jsonplaceholder.typicode.com/posts/' + (1+$(this).index()), renderHTML); } function renderHTML(data) { // This particular JSON request returns an object with body property var htmlS = data.body; $('#main_ima').html(htmlS); } // On page load, click on the first `li` to automatically load the data for it $('#liste > li:first').click(); 
 #liste { width: 40px } .active { background: yellow } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ol id="liste"> <li class="active">load 1</li> <li>load 2</li> <li>load 3</li> </ol> <div id="main_ima"></div> 

The following answers your main concern, how to dynamically get the ID with jquery: 以下是您主要关心的问题,即如何使用jquery动态获取ID:

 $('.listen-to-me').click(function() { //Add event listener to class var elementId = $(this).attr('id'); //Get the 'id' attribute of the element clicked var idNumber = elementId.substring(elementId.indexOf("-") +1); //Get the index of the "-" in the string, and then cut everything prior alert(idNumber); //The final result }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li id="test-1" class="listen-to-me">1</li> <li id="test-2" class="listen-to-me">2</li> <li id="test-3" class="listen-to-me">3</li> <li id="test-4" class="listen-to-me">4</li> <li id="test-5" class="listen-to-me">5</li> </ul> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM