简体   繁体   English

如何动态使html元素获取其ID?

[英]How to dynamically make html element get its ID?

So I have something like this:所以我有这样的事情:

 <button id="select-settings-<var2 CardID>-{substrCardNumb(<var2 CardAccID>)}">

The function just returns the last digits of the given variable.该函数只返回给定变量的最后一位。

Obviously this doesn't work, but what im trying to do is dynamically generate an ID for different cards.显然这不起作用,但我试图做的是为不同的卡动态生成一个 ID。 The var2-s come from the server and currently I'm getting the full length for cardAccID, but I only want the last 4 digits to be in the ID of the html element. var2-s 来自服务器,目前我正在获取 cardAccID 的完整长度,但我只希望最后 4 位数字位于 html 元素的 ID 中。

How do I insert inline javascript functions into an id?如何将内联 javascript 函数插入 id?

I found a solution that works for me.我找到了一个适合我的解决方案。 What I'm doing here is maping through all the elements that I know contain a button to which I want to add an ID.我在这里所做的是映射所有我知道的元素,这些元素包含一个我想添加一个 ID 的按钮。 From those buttons I select the first button because that's the one I care about right now.从这些按钮中,我选择了第一个按钮,因为这是我现在关心的那个。 I split the buttons current ID, which is "select-settings-randomnumbers".我拆分了按钮的当前 ID,即“select-settings-randomnumbers”。 I get an array of 3 and I take the last element [2] and with substring() I get the last 4 digits of that element.我得到一个 3 的数组,我取最后一个元素 [2] 并使用 substring() 我得到该元素的最后 4 位数字。 I later replace the number at array[2] with the newly gotten 4 digits.我后来用新得到的 4 位数字替换了 array[2] 处的数字。

jQuery(document).ready(function(){
 jQuery(".cards__content__card__list-item__actions").each(function(){
    let button = jQuery(this).find("button").eq(0)
    let splitId = button.attr("id").split("-")
    let cutId = splitId[2].substring(splitId[2].length -4)
    splitId[2] = cutId
    button.attr("id", splitId.join("-"))
 })

}) })

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

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