【问题标题】:Use variable as jQuery selector使用变量作为 jQuery 选择器
【发布时间】:2016-05-26 01:46:35
【问题描述】:

我正在尝试将变量用作 jQuery 选择器,但它在控制台中输出错误:

错误:语法错误,无法识别的表达式:# in jquery.2.1.4.min.js

有人解释为什么会发生这种情况吗?

function FileSelected(file) {
    var imgId = RoxyUtils.GetUrlParam('img');
    $(window.parent.document).find("#" + imgId).attr('src', file.fullPath);
    $(window.parent.document).find("#" + imgId).next().val(file.fullPath);
    window.parent.closeCustomRoxy();
}

【问题讨论】:

  • imgId 的值是多少
  • 尝试在定义变量var imgId= "#"+RoxyUtils.GetUrlParam('img'); 时添加主题标签。另外,请在定义后立即console.log(imgId);,让我们知道你看到了什么。
  • img的id attr。例如:“img1”。
  • 只有.find('#') 在我的控制台中给出了这个错误,所以我假设imgId 是空白、空等。
  • 抱歉,我没有看到 BenG 的评论。我发布了类似的答案

标签: javascript jquery html jquery-selectors


【解决方案1】:

使用上下文参数,你可以尝试使用下面的方式......

function FileSelected(file){
 /**
 * file is an object containing following properties:
 * 
 * fullPath - path to the file - absolute from your site root 
*/
 var imgId= RoxyUtils.GetUrlParam('img');
 $("#"+imgId,window.parent.document).attr('src', file.fullPath);
 $("#"+imgId,window.parent.document).next().val(file.fullPath);

 window.parent.closeCustomRoxy();
}

【讨论】:

    【解决方案2】:

    如果你可以改变:

    var imgId = '#' + RoxyUtils.GetUrlParam('img').toString(); //append # in the image ID, and change to string, if returning an integer.
    $(window.parent.document).find(imgId).attr('src', file.fullPath);
    $(window.parent.document).find(imgId).next().val(file.fullPath);
    

    那么,它应该可以工作了。

    告诉我

    【讨论】:

      【解决方案3】:

      刚刚添加了一个 if else 以确保 imgId 不为空。

      function FileSelected(file) {
                  var imgId = RoxyUtils.GetUrlParam('img');
                  if(imgId.trim().length >0){
                         $(window.parent.document).find("#" + imgId).attr('src', file.fullPath);
                         $(window.parent.document).find("#" + imgId).next().val(file.fullPath);
                         window.parent.closeCustomRoxy();
                  }
                  else{
                    console.log("the value of imgId is : " + imgId);
                  }           
              }
      

      确保您的 imgId 的值中没有“#”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多