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

时间:2016-02-02 06:31:49

标签: javascript jquery

这是动态创建的元素:

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

我想为它添加以下属性:

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

我试过了:

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

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

最好的方法是什么?

3 个答案:

答案 0 :(得分:1)

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

@echo on

CD /D %~dp0
SET DEPOT_TOOLS_WIN_TOOLCHAIN=0
SET DEPOT_TOOLS=%CD%/depot_tools
SET PYTHONHOME=%DEPOT_TOOLS%/python276_bin
SET PYTHONPATH=%CD%/v8/build/gyp
SET PATH=%DEPOT_TOOLS%;%PYTHONHOME%;%PATH%

SET GYP_DEFINES=target_arch=x64
REM SET GYP_DEFINES=target_arch=x64 component=shared_library v8_use_snapshot=false
REM About GYP_DEFINES: https://github.com/v8/v8/wiki/Building-with-Gyp

IF EXIST %DEPOT_TOOLS% (
  ECHO Updating depot_tools
  CD %DEPOT_TOOLS%
  CALL git pull
  CD ..
) ELSE (
  ECHO Getting depot_tools
  CALL git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git
)

CALL gclient
CALL gclient config https://chromium.googlesource.com/v8/v8.git
CALL gclient sync

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

$(element).attr("data-x")$(element).data("x")不同。

jQuery api : .data()

试试这个:

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