jQuery:使用变量作为选择器

标签 jquery variables jquery-selectors

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

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


    });

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

如果您能指导我做错了什么以及如何纠正它,我将不胜感激。

谢谢

最佳答案

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

关于jQuery:使用变量作为选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17097947/

相关文章:

javascript - 何时使用 this.var 和 var = ;在 javascript 函数 obj 中?

javascript - 如何从javascript或jquery中的元素数组中删除特定元素

javascript - 两个按钮像单选按钮一样改变类,但一次只有一个

javascript - parseInt() 导致 javascript 函数的返回值是预期结果的 0.77 倍,基数指定为十进制

javascript - 每个按钮单击 : jQuery 时, map 都会附加到模态主体

javascript - $ ("#slider").easySlider 不是函数

javascript - for 循环中的变量

Java 系统属性和环境变量

javascript - 如何使用 javascript 查找特定的子元素

javascript - 在 JavaScript 中过滤 JSON 子对象