小编dor*_*ich的帖子

jQuery:使用变量作为选择器

我在使用变量作为我想要采取行动的段落的选择器时遇到问题.具体来说,我有几个标题元素和相同数量的段落.期望的结果是,如果我点击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 …
Run Code Online (Sandbox Code Playgroud)

variables jquery jquery-selectors

55
推荐指数
1
解决办法
13万
查看次数

标签 统计

jquery ×1

jquery-selectors ×1

variables ×1