【问题标题】:How to dynamically make html element get its ID?如何动态使html元素获取其ID?
【发布时间】:2022-07-06 22:26:29
【问题描述】:

所以我有这样的事情:

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

该函数只返回给定变量的最后一位。

显然这不起作用,但我试图做的是为不同的卡动态生成一个 ID。 var2-s 来自服务器,目前我正在获取 cardAccID 的完整长度,但我只希望最后 4 位数字位于 html 元素的 ID 中。

如何在 id 中插入内联 javascript 函数?

【问题讨论】:

  • 您可以在 JavaScript 代码中生成 HTML 字符串,然后使用 element.innerHTML API 将它们添加到 DOM 中。 developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
  • 你不能用 PHP 做这个吗?
  • 不,我们的堆栈是 javascript 和 jquery
  • @im_tsm innerhtml 添加 html 文本是的,但我正在尝试设置 ID。我试过 element.id += substrCardNumb(.....),但它似乎不起作用
  • @neuromancer 你能提供更多代码吗?

标签: javascript html frontend wml


【解决方案1】:

我找到了适合我的解决方案:

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("-"))
 })

})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2020-04-23
    • 2012-10-19
    • 1970-01-01
    相关资源
    最近更新 更多