如何在li中动态获取动态创建的ID [英] How to dynamically get the dynamically created ID in a li

查看:69
本文介绍了如何在li中动态获取动态创建的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试学习js(以及一堆jquery),并且在尝试找到一种结合我所找到的解决方案的方法时遇到了两个困难.

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很陌生.

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.

因此,我先从基本的html开始,再加上几个li.

So I start with a basic html with a few li.

<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> 

我想为每个"li"创建一个id,因此在main.js中添加以下代码:

I want to create ids for each "li" so in my main.js I add this:

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

到目前为止效果很好.每当我添加一个新的li时,它都会得到一个新的id.我还将它放入var中,因为以后需要使用它.

This works great so far. Everytime I add a new li, it gets a new id. I also put it into a var because I will need to use it later.

在控制台中,如果输入idVar,它将显示li的整个列表.如果我输入idVar [3].它只给了我与[3]关联的li.完美.

In th console, If I type idVar, it gives me the whole list of li. If I type idVar[3]. it only gives me the li associated to the [3]. Perfect.

现在,当我单击li之一时,我想让某些东西出现.例如,我将使用[3].所以我将其添加到main.js

Now I want to get something to appear when one of the li is clicked. For example, I will use the [3]. So I add this to my 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);

}

请注意,我为CSS添加了添加/删除活动"类.

Just a side note, I added the add/remove "active" class for CSS.

因此,当我单击li [3]时,它几乎可以正常工作.唯一的事情是,当我重新单击[3]时,它将第二次产生结果.再一次,如果我第三次单击它,它将第三次产生结果,而不会删除过去的结果. (这不完全是我想要的.只是第一个结果会更好.)

So when I click the li[3], it works almost as expected. The only thing is when I reclick [3] it produces the result a 2nd time. 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.

我希望根据单击的li的ID动态检测[number].我可以以非常难看的方式为我拥有的每个[数字]复制并粘贴此代码.它会工作.但是,如果我想添加更多li元素,我将需要添加以上代码的更多副本和粘贴,这可能给我带来无数的庞大文件.虽然可以,但这肯定不是最好的方法.

I would like the [number] to be dynamically detected, based on the id of the clicked li. 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. 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. :)

然后,将动态添加到单击的li后,我也希望根据li id动态更改链接.例如,代替:

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. For example, instead of :

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

类似:

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

var等于单击的li的[3]数字.

the var being equal to the [3] number of the clicked li.

在这种情况下,当我尝试使用for循环添加var时,总是得到"var = max.length"而不是"var = [clicked id]".

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]".

因此,您已经拥有了它.您需要更多详细信息吗?

So there you have it. Do you need more details?

这是我第一次尝试JS和/或Jquery.我已经玩了几天,但是当我寻找答案时,当我实现解决方案"时,总是给我带来一些新问题.因此,我向您展示了与我正在寻找的最接近的IMO代码.

This is my first JS and/or Jquery try. 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.

希望我离可行的事情不太远,而且不如我的解决方案那么大. :)

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.

推荐答案

以下是一些建议:

  • 您不需要为li分配id属性.实际上,您永远不需要id.这也将起作用(请注意选择器中的>,这使得find调用不再必要):

  • You don't need to assign id attributes to your li. You actually never need that id. This will work just as well (note also the > in the selector which makes the find call unnecessary):

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

现在,您可以将每个li称为$li[3],尽管这不是最佳实践".更好的是$li.get(3).我也喜欢约定,当它是jQuery选择的结果时,以$开头变量.它提供了一个提示,您可以将jQuery方法应用于该提示.

Already now you can address each of the li as $li[3], although that is not the "best practise". Better is $li.get(3). I also like the convention to start the variable with $ when it is the result of a jQuery selection. It gives a clue that you can apply jQuery methods to it.

您不需要为每个li分别分配一个点击处理程序.使用jQuery on(而不是本机的addEventListener),您可以一次为所有事件分配一个事件处理程序.

You don't need to assign a click handler to each li separately. With jQuery on (instead of the native addEventListener) you can assign one event handler for all of them at once.

$li.on('click', apar) 

  • 您为on定义的回调将this设置为已单击的特定li元素,因此您可以执行以下操作:

  • The callback you define for on will have this set to the particular li element that has been clicked, so you can do:

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

    ...无需任何数组查找.

    ... without any array lookup.

    jQuery为多种类型的HTTP请求提供了简单的功能,因此您无需使用XMLHttpRequest.实际上,有一个专门用于获取JSON的代码,因此您甚至不必解析响应:

    jQuery offers easy functions for several types of HTTP requests, so you don't need to use XMLHttpRequest. In fact, there is one specifically for getting JSON, so you don't even have to parse the response:

    $.getJSON('https://domain.link.to.file.json', renderHTML);
    

  • jQuery index()方法可以为您提供该li的序列号:

  • The jQuery index() method can give you the sequence number of that li:

    $.getJSON('https://domain.link.to.file' + $(this).index() + '.json', renderHTML);
    

  • 要替换某个元素的内部HTML,可以使用jQuery html方法:

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

    还要注意,您不需要DOM本机的getElementById方法,jQuery可以用简短的$('#main_ima')为您查找.

    Note also how you don't need the DOM native getElementById method, jQuery can look that up for you with the short $('#main_ima').

    这是一个使用伪造的JSON服务服务器的有效示例:

    Here is a working example with a fake JSON serving server:

    $("#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>

    这篇关于如何在li中动态获取动态创建的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆