Javascript Jquery - 通过在字符串中构造 id 的 id 获取元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4325278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:54:43  来源:igfitidea点击:

Jquery - Get element by id constructing the id in string

javascriptjquery

提问by Samuel Beckett

I have a trouble using an element with jquery. I am constructing the name in a var such as:

我在 jquery 中使用元素时遇到问题。我在 var 中构造名称,例如:

var myId = "#" + myGotId;

$(myId).attr("title", "changed");

$(myId) is returning empty. I would want to get my element by id but constructing my Id dynamically joining strings.

$(myId) 返回空。我想通过 id 获取我的元素,但动态地构建我的 Id 加入字符串。

edit by @Pointy— additional code supplied in a comment by the OP:

由@Pointy 编辑— OP 在评论中提供的附加代码:

var form = $('form#formDefaultValue');
$(':submit', form).click(function(event) {
  event.preventDefault();
  $.post(form.attr('action'), form.serialize(), function(data, status, XMLHttpRequest) {
    if (status == 'success') {
      $("#msgInformation").html("Your changes have been successfully saved.");
      jQuery("#spanDefaultValue").attr("class", "db");
      var g = indexNodeSelected;
      g = g.replace("\", "\\\\");
      $('#'+ g).find("span").attr("class", "");
   } 

回答by Pointy

I don't know exactly what is happening because you have not posted much code, but make sure that your Javascript code is running afterthe element with your target "id" value has been included in the DOM. If you have this:

我不知道到底发生了什么,因为您没有发布太多代码,但是请确保具有目标“id”值的元素已包含在 DOM 中之后,您的 Javascript 代码正在运行。如果你有这个:

<html>
  <head>
    <script>
      var myId = '#' + myGotId;
      $(myId).whatever();

then that won't work because the actual page will not have been seen when your code runs.

那么这将不起作用,因为在您的代码运行时不会看到实际页面。

Instead, try this:

相反,试试这个:

  <script>
    $(function() {
      var myId = '#' + myGotId;
      // ...
    });

It is also important to make sure that your "myGotId" string is exactly the value you expect (that is, the value coded into the "id" attribute of your target element).

确保您的“myGotId”字符串正是您期望的值(即编码到目标元素的“id”属性中的值)也很重要。

editIf you think that you're correctly constructing the "id", then you could try this as an alternative:

编辑如果您认为您正确构建了“id”,那么您可以尝试将其作为替代方案:

$(document.getElementById(myGotId)).whatever()

In other words, you can "wrap" a plain DOM element up in a jQuery object by just passing to the $()function. If that works, then the problem could be that your "id" value is somehow confusing the selector engine. Does the "id" value contain "." by any chance?

换句话说,您可以通过传递给$()函数来将一个普通的 DOM 元素“包装”在一个 jQuery 对象中。如果可行,那么问题可能在于您的“id”值以某种方式混淆了选择器引擎。“id”值是否包含“.” 在任何情况下?

回答by Mike Grace

The reason your jQuery isn't working as expected is because it is executing before the DOM is fully loaded into the browser.

您的 jQuery 没有按预期工作的原因是它在 DOM 完全加载到浏览器之前执行。

Put your jQuery code in a document ready function and it will work.

将您的 jQuery 代码放在文档就绪函数中,它将起作用。

$(document).ready(function () {
  // code that will run once the entire DOM is loaded into the browser
});

Example webpage => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-get-element-by-constructed-string.html

示例网页 => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-get-element-by-constructed-string.html

Example Firebug console output

Firebug 控制台输出示例

Example Firebug console output

Firebug 控制台输出示例

What happened here?

这里发生了什么?

  1. as soon as the script loaded it started executing
  2. console.log output 'Dom may not be ready yet'
  3. jQuery selector returned nothing
  4. DOM fully loaded into browser starting the document ready function
  5. jQuery selector returned expected results
  1. 脚本一加载就开始执行
  2. console.log 输出 'Dom 可能还没有准备好'
  3. jQuery 选择器没有返回任何内容
  4. DOM 完全加载到浏览器中,启动文档就绪功能
  5. jQuery 选择器返回预期结果

Why?

为什么?

Scripts can load before a browser has a chance to parse the HTML on a page. Before a browser can fully parse the DOM and build it's DOM tree it won't be able to tell you if an element exists or not. This is why running the jQuery selector before the document is ready will often result in unexpected results.

脚本可以在浏览器有机会解析页面上的 HTML 之前加载。在浏览器可以完全解析 DOM 并构建它的 DOM 树之前,它无法告诉您元素是否存在。这就是为什么在文档准备好之前运行 jQuery 选择器通常会导致意想不到的结果。

Example script

示例脚本

//run possibly before DOM is loaded into browser
var selector = "#crazy-image";
console.log("DOM may not be ready yet");
console.log($(selector));
$(document).ready(function () {
  // code that will run once the entire DOM is loaded into the browser
  console.log("DOM ready");
  console.log($(selector));
});

回答by ryanulit

Do you need the extra variable? Try without it, like this:

你需要额外的变量吗?尝试没有它,像这样:

$("#" + myGotId).attr("title", "changed");  

回答by Steren

As this example show, your code should be working : Make sure you execute the script after the element you want to get has been created. Make sure the id is correct.

如本示例所示,您的代码应该可以正常工作:确保在创建要获取的元素后执行脚本。确保 id 正确。

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>

<div id="mydiv">Hello</div>

<script>
var myGotId = 'mydiv';
var myId = "#" + myGotId;
$(myId).attr("title", "changed");
</script>

</body>
</html>