【问题标题】:jQuery: using a variable as a selector [duplicate]jQuery:使用变量作为选择器[重复]
【发布时间】:2013-06-10 11:32:18
【问题描述】:

我在使用变量作为我要对其执行操作的段落的选择器时遇到问题。 具体来说,我有几个标题元素和相同数量的段落。期望的结果是,如果我点击 Title1,然后我对段落 1 采取行动。我为开发目的做了一个简单的案例,如果我点击一个标题,那么相应段落的文本就会改变颜色。 如果我对解决方案进行硬编码,它可以工作,但在选择器失败时传入一个变量。

jQuery如下:

    jQuery(document).ready(function($){
       $(this).click(function(){

        var target=(event.target.id);// Get the id of the title on which we clicked. We will extract the number from this and use it to create a new id for the section we want to open.
        alert(target);// checking that we are getting the right value.
        var openaddress=target.replace(/click/gi, "section");//create the new id for the section we want to open.
        alert('"#'+openaddress+'"');//Confirm that the correct ID has been created
        $('"#'+openaddress+'"').css( "color", "green" );//get the id of the click element and set it as a variable.
        //$("#section1").css( "color", "green" );//Test to confirm that hard coded selector functions correctly.

            return false;// Suppress the action on the anchor link.
            });


    });

警报返回以下变量 这似乎是正确的并且与硬编码版本匹配。 我省略了 html,因为它在硬编码版本中工作,我认为这方面没有问题。

对于我做错了什么以及如何纠正它的任何指导,我将不胜感激。

谢谢

【问题讨论】:

  • 尝试省略 "#section1" 周围的第二个引号,以便实际传递给 jQuery 的字符串将根据需要为 #section1。如果这是有道理的。尝试传递'#' + openaddress。请注意,您的代码通过 "#section1" 并且您的测试使用 #section1
  • $("#foo") 中的"#foo" 称为字符串文字,它产生字符串value #foo。字符串文字由两个引号(双引号或单引号)表示。这与其他值类似:[...] 表示一个数组,/.../ 表示正则表达式文字,{...} 一个对象等。这些符号告诉解析器如何解释字符序列。它们本身不是价值的一部分!因此,jQuery 期望 #foo 作为选择器,但您在值中包含引号并传递 '#foo',这是不正确的。
  • @FelixKling:感谢您的帮助。我不清楚字符串文字和 jQuery 使用的值。我需要解释,因此“重复”问题对我没有帮助(但只是因为我的无知。)
  • @RyanE:谢谢,我想我现在明白了。

标签: jquery variables jquery-selectors


【解决方案1】:

你想得太复杂了。实际上只是$('#'+openaddress)

【讨论】:

  • 该死的救生员!谢谢:)
  • 您也可以使用template literals (`)。在你的情况下$(`${openaddress}`)
猜你喜欢
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
  • 1970-01-01
  • 2013-02-13
相关资源
最近更新 更多