【问题标题】:Undefined Javascript variable - phcat未定义的 Javascript 变量 - phcat
【发布时间】:2017-04-19 19:25:49
【问题描述】:

我有一个返回未定义变量的函数。我尝试了一些类似帖子中的所有回复,但没有结果。

identifier_id 已定义,但 phcat 未定义。有任何想法吗?

$(function() {
  $('body').on('click', '.save_random_profile', function() {
    var identifier_id = $(this).attr("id");
    $('.created_profile' + identifier_id).html('<img src="img/loader.gif" class="loading" />'); 
     var phcat =  document.getElementById('#phcat'+identifier_id).value; 
    alert(phcat);

    $.ajax({
      type: "POST",
      async: false,
      url: "actions/save_random_profile.php",
      data: dataString,
      cache: false,
      success: function(data) {
        if (data == 0) {
          $('.created_profile' + identifier_id).html('Not Sent!');
        } else {
          $('.created_profile' + identifier_id).html(data);
        }
      }  
    });
    return false;
  });
});

【问题讨论】:

  • 获取id 选择的元素的id 有什么意义 - 您已经在identifier_id 中拥有该值。问题本身是因为 jQuery 对象没有 id 属性。您需要改用.prop('id') - 尽管正如我之前所说,这完全是多余的代码。
  • var phcat = $('.phcat#' + identifier_id).id; to var phcat = $('.phcat#' + identifier_id).attr('id');
  • 更改为 var phcat = $('.phcat#' + identifier_id).id; 并检查 .但是这里的.id 是什么?我认为它需要是 .val().text()attr('id') .. 类似的东西
  • @RoryMcCrossan 如果你仔细看,我会得到一个值,它存储为像输入表单这样的对象的 id。每个输入表单都有一个唯一的 id,它等于 label+unique_identifier。每个 id 的值将被存储为变量,然后发布到 php 脚本。
  • @RoryMcCrossan,对不起,我的代码出错了。现在更新了!

标签: javascript jquery


【解决方案1】:

试试jquery.attr()

Object.id 是原生 javascript 方法,不适用于 jquery 集合对象。

要获取 jquery 对象中的 id,请使用 var phcat = $('.phcat#' + identifier_id).attr("id");

或者如果你想坚持使用 javascript,请使用 document.querySelector('.phcat#' + identifier_id).id;

$(function() {
  $('body').on('click', '.save_random_profile', function() {
    var identifier_id = $(this).attr("id");
    $('.created_profile' + identifier_id).html('<img src="img/loader.gif" class="loading" />'); 
    var phcat = $('.phcat#' + identifier_id).attr("id");
    alert(phcat);

    $.ajax({
      type: "POST",
      async: false,
      url: "actions/save_random_profile.php",
      data: dataString,
      cache: false,
      success: function(data) {
        if (data == 0) {
          $('.created_profile' + identifier_id).html('Not Sent!');
        } else {
          $('.created_profile' + identifier_id).html(data);
        }
      }  
    });
    return false;
  });
});

编辑

如果您使用的是document.getElementById,请不要将# 与id 一起使用。

var phcat =  document.getElementById('phcat'+identifier_id).value; 

【讨论】:

  • 抱歉,我的代码出错了。现在更新了!
【解决方案2】:

使用var phcat = $('.phcat#'+identifier_id).attr('id');

【讨论】:

  • 请解释你的答案
  • 对不起,我的代码出错了。现在更新了!
【解决方案3】:

使用

var phcat = $('.phcat#' + identifier_id)[0].id;

它会给你原生 JS obj

var phcat = $('.phcat#' + identifier_id).attr('id');

它会返回元素的id

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2018-08-06
    • 2018-06-23
    • 2021-12-21
    • 2012-01-16
    相关资源
    最近更新 更多