jQuery:使用变量作为选择器 [英] jQuery: using a variable as a selector

查看:79
本文介绍了jQuery:使用变量作为选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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,因为它可以在硬编码版本中使用,我认为那边没有问题.

The alert returns the following variable which appears to be correct and matches the hard coded version. I've omitted the html since it works in the hard coded version I assume there is no problem on that side.

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

I'd appreciate any guidance on what I'm doing wrong and how to correct it.

谢谢

推荐答案

您认为太复杂了.实际上只是$('#'+openaddress).

You're thinking too complicated. It's actually just $('#'+openaddress).

这篇关于jQuery:使用变量作为选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆