I'm having problems using a variable as the selector for a paragraph on which I want to take action. Specifically I have several title elements and the same number of paragraphs. The desired result is that if I click on Title1 then I take an action on paragraph1. I made a simple case for development purposes whereby if I click on a title then the text of the corresponding paragraph changes color. If I hard code the solution it works but passing in a variable as the selector fails.

The jQuery is as follows:

    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 返回以下变量 返回的alert 显示变量的值 其看起来是正确的并且与硬编码版本匹配. 我省略了html,因为它在硬编码版本中工作,我想那一侧没有问题.

如果有任何关于我做错了什么以及如何改正的指导,我将不胜感激.

谢谢

推荐答案

你的 idea 太复杂了.实际上只有$('#'+openaddress)美元.

Jquery相关问答推荐

ASP.NET MVC - Ajax 将空值传递给控制器

Flask,如何为ajax调用返回成功状态码

禁用提交按钮,直到所有字段都有值

如何从 jQuery 转到 React.js?

如何在 jquery 中包含 !important

jquery如何捕获输入键并将事件更改为选项卡

我如何从 ACE 编辑器中获得价值?

如何使用jQuery找到元素顶部的垂直距离(以px为单位)

从 iframe 访问父窗口的元素

使用 jQuery DataTables 时禁用最后一列的排序

使用 Jquery 更改页面标题

使用 jquery 通过文本设置下拉值

使用 jQuery 获取 div 的可见高度

jQuery: Select 所有具有自定义属性的元素

设置 JQuery event.preventDefault() 时绕过 window.open 上的弹出窗口阻止程序

将数据发布到 JsonP

你如何记录jQuery中一个元素触发的所有事件?

如何获取 jQuery 下拉值 onchange 事件

catch forEach 最后一次迭代

jQuery:通过 .attr() 添加两个属性;方法