Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

javascript - 简化不同选择器的重复onclick事件(Simplifying repeated onclick events for different selectors)

I have 3 img elements with ID's.

(我有3个具有ID的img元素。)

When I click the element, I change the img src like this

(当我单击元素时,我会像这样更改img src)

$("#employee").on("click", function(){
    var x = $(this);

    var y = $(this).attr("src");

    if($(this).attr("src") == "images/employee.svg")
    {
            $(this).attr("src", "images/employee_selected.svg");
    }

    else
    {
            $(this).attr("src", "images/employee.svg");
    }
});

$("#team").on("click", function(){
    var x = $(this);

    var y = $(this).attr("src");

    if($(this).attr("src") == "images/team.svg")
    {
            $(this).attr("src", "images/team_selected.svg");
    }

    else
    {
            $(this).attr("src", "images/team.svg");
    }
});

$("#product").on("click", function(){
    var x = $(this);

    var y = $(this).attr("src");

    if($(this).attr("src") == "images/product.svg")
    {
            $(this).attr("src", "images/product_selected.svg");
    }

    else
    {
            $(this).attr("src", "images/product.svg");
    }
});

This code seems to be awfully repetitive and I was wondering if there was a way to do this in a single .on click function using something like a switch statement.

(这段代码似乎非常重复,我想知道是否有一种方法可以在单个.on click function使用switch语句之类的方法。)

How could I simplify this into a single statement?

(如何将其简化为一个语句?)

  ask by JuiceBox translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Consider the following code:

(考虑以下代码:)

 $(function() { $(".svg").on("click", function() { var x = $(this); var non = "images/" + x.attr("id") + ".svg"; var sel = "images/" + x.attr("id") + "_selected.svg"; if (x.attr("src").indexOf("_") < 0) { x.attr("src", sel).toggleClass("selected"); console.log(sel); } else { x.attr("src", non).toggleClass("selected"); console.log(non); } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <img id="employee" src="images/employee.svg" class="svg image" /> <img id="team" src="images/team.svg" class="svg image" /> <img id="product" src="images/employee.svg" class="svg image" /> </div> 

We can extract the SRC of the element that was clicked and based on a specific condition, perform a specific action.

(我们可以提取被单击元素的SRC ,并根据特定条件执行特定操作。)

This works for all elements with the class selector, svg .

(这适用于所有带有类选择器svg元素。)

Hope that helps.

(希望能有所帮助。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...