Jquery - 通过id在string中构造id来获取元素 [英] Jquery - Get element by id constructing the id in string

查看:136
本文介绍了Jquery - 通过id在string中构造id来获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用带有jquery的元素时遇到了麻烦。我在var中构造名称,例如:

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

var myId = "#" + myGotId;

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

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

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

编辑@Pointy — OP在评论中提供的其他代码:

edit by @Pointy — additional code supplied in a comment by the 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", "");
   } 


推荐答案

我完全不知道发生了什么事,因为你没有发布很多代码,但确保你的Javascript代码在之后运行元素中包含你的目标id值。如果你有这个:

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

<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.

相反,试试这个:

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

确保myGotId字符串与您期望的值完全相符也很重要(是,编码到目标元素的id属性中的值。)

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).

编辑如果您认为您正确构建了id,然后你可以尝试这个替代:

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

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

换句话说,你可以通过传递将一个普通的DOM元素包装在jQuery对象中到 $()函数。如果这样做,那么问题可能是你的id值在某种程度上混淆了选择器引擎。 id值是否包含。什么机会?

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?

这篇关于Jquery - 通过id在string中构造id来获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆