如何使用Jquery修改动态生成的元素而不使用click()?

时间:2021-12-26 09:47:05

This is the dynamically created element:

这是动态创建的元素:

<th style="" data-field="realName">
  <div class="th-inner ">Name</div>
  <div class="fht-cell"></div>
</th>

And I want to add the following attribute to it:

我想为它添加以下属性:

$("th[data-field='realName']").attr("data-i18n", "realName");
$("th[data-field='realName']").i18n();

I tried this:

我试过这个:

$(document).on("trigger", "th[data-field='realName']", function (e) {
   $("th[data-field='realName']").attr("data-i18n", "realName");
   $("th[data-field='realName']").i18n();
})

But it didn't work---the attribute wasn't assigned.

但它不起作用---属性未分配。

What's the best way to do this?

最好的方法是什么?

3 个解决方案

#1


1  

I always use querySelector/querySelectorAll instead of jquery.

我总是使用querySelector / querySelectorAll而不是jquery。

var elements = document.querySelectorAll(th[data-field='realName']);
for(var i = 0; i < elements.length; i++)
{
    elements[i].setAttribute("data-i18n", "realName");
}

or

var element = document.querySelector(th[data-field='realName']);
if(element)
    element.setAttribute("data-i18n", "realName");

#2


1  

I think the code should be like this:

我认为代码应该是这样的:

$("th").each(function(){
  if ($(this).data("field") == "realName"){
    $(this).attr("data-i18n","realName");
  }
});

#3


0  

$(element).attr("data-x") and $(element).data("x") are different.

$(元素).attr(“data-x”)和$(元素).data(“x”)是不同的。

jQuery api : .data()

jQuery api:.data()

try this:

 $("th[data-field='realName']").data("i18n", "realName");
   $("th[data-field='realName']").data("i18n");

#1


1  

I always use querySelector/querySelectorAll instead of jquery.

我总是使用querySelector / querySelectorAll而不是jquery。

var elements = document.querySelectorAll(th[data-field='realName']);
for(var i = 0; i < elements.length; i++)
{
    elements[i].setAttribute("data-i18n", "realName");
}

or

var element = document.querySelector(th[data-field='realName']);
if(element)
    element.setAttribute("data-i18n", "realName");

#2


1  

I think the code should be like this:

我认为代码应该是这样的:

$("th").each(function(){
  if ($(this).data("field") == "realName"){
    $(this).attr("data-i18n","realName");
  }
});

#3


0  

$(element).attr("data-x") and $(element).data("x") are different.

$(元素).attr(“data-x”)和$(元素).data(“x”)是不同的。

jQuery api : .data()

jQuery api:.data()

try this:

 $("th[data-field='realName']").data("i18n", "realName");
   $("th[data-field='realName']").data("i18n");