문제

<div id="calcwrapper">
    <img class="sugarcube" src="images/sugarcube.png" width="13" height="17">
    <div id="drinks">
        <a id="drink1" href=""><img src="images/drinkicon1.png" width="84" height="81"></a><div class="drink1"></div>
    </div>
</div>

In the example above there is only the single drink button, but my code contains eight buttons. Each with a corresponding same-named classed div. What I'm trying to do is "dynamically" grab the id of the anchor tag (id="drink1") to append a clone sugarcube image (img class="sugarcube" ...) into the equivalent class name div (class="drink1"). I hope that doesn't sound confusing. Perhaps the unsuccessful attempts below will give you some idea of what I am trying to achieve.

Attempt 1

$(".sugarcube").clone().attr("class", "sugarcube" + i).appendTo($(this).parent((".drink1").attr("class")));

Attempt 2 (trying to find a working solution via the console)

var className = $(this).attr("id");
console.log(className);

console.log($(this).parent().children("div").hasClass(className));

I've searched Google and StackOverflow and haven't found any code samples. Thank you for your help.

Here's the complete HTML code context...

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
    <script src="js/jquery-animate-css-rotate-scale.js"></script>
    <script>
        $(function() {
            $(".sugarcube").hide();
            var max = 8;
            function animateSugarcubes() {
                for (var i=1; i<=max; i++) {
                    $(".sugarcube" + i).css("position", "absolute");
                    $(".sugarcube" + i).css("top", Math.ceil(Math.random() * (50 - 20) + 20));
                    $(".sugarcube" + i).css("left", Math.ceil(Math.random() * (85 - 40) + 40));
                    $(".sugarcube" + i).hide();
                }
            }

            $("#drinks a").click(function() {

                for (var i=1; i<=max; i++) {
                    // Attempt 1
                    $(".sugarcube").clone().attr("class", "sugarcube" + i).appendTo($(this).parent().children($(this).attr("id")));

                    // Attempt 2 test code.
                    var className = $(this).attr("id");
                    console.log($(this).parent().children("div").hasClass(className));
                }

                return false;
            });
            animateSugarcubes();
        }); 
    </script>
</head> 
<body> 

<div id="calcwrapper">
    <img class="sugarcube" src="images/sugarcube.png" width="13" height="17">
    <div id="drinks">
        <a id="drink1" href=""><img src="images/drinkicon1.png" width="84" height="81"></a><div class="drink1"></div>
        <a id="drink2" href=""><img src="images/drinkicon2.png" width="84" height="81"></a><div class="drink2"></div>
        <a id="drink3" href=""><img src="images/drinkicon3.png" width="84" height="81"></a><div class="drink3"></div>
        <a id="drink4" href=""><img src="images/drinkicon4.png" width="80" height="81"></a><div class="drink4"></div>
        <a id="drink5" href=""><img src="images/drinkicon5.png" width="84" height="81"></a><div class="drink5"></div>
        <a id="drink6" href=""><img src="images/drinkicon6.png" width="84" height="81"></a><div class="drink6"></div>
        <a id="drink7" href=""><img src="images/drinkicon7.png" width="84" height="81"></a><div class="drink7"></div>
        <a id="drink8" href=""><img src="images/drinkicon8.png" width="84" height="81"></a><div class="drink8"></div>
    </div>
</div>

</body> 
</html> 

Please note that the anchor tag uses an id (id="drink1") while the div uses a class (class="drink1")

도움이 되었습니까?

해결책

If I answer your question literally then I might end up with something like this:

var drinksLinks = $("#drinks a"); // get list of all a tags inside drinks
drinksLinks.each(function() {     // perform function for each element
   var element = $(this);         // get jquery object for the current element
   var id = element.attr("id");   // get the id
   var div = element.find("." + id); // find the element with class matching the id

   $(".sugarcube").clone().appendTo(div);
});

However, you should try to avoid referencing things by class if you are trying to find one specific element. My suggestion would be to actually just assume that a div such as drinks1 is always right next to the a tag, then you can do something like:

var sugarcube = $(".sugarcube");
var drinksLinks = $("#drinks a"); // get list of all a tags inside drinks

drinksLinks.each(function() {
   var div = $(this).next();  // get the element next to the a tag
   sugarcube.clone().appendTo(div);
});

A couple of things to remember:

  • Try to make your selectors as narrow as possible as searching the DOM can be expensive.
  • Try to search the DOM by id where possible as this is is natively faster than by class in older browsers
  • If you are making multiple references to the same element, store it in a variable like I have with the sugarcube element. This way you cut down the amount of searches of the page you need in order to achieve the result

Hope this helps!

다른 팁

If you are using elements with an identifier, then use "class" instead of an "id". "id" should be unique. In the given example its used for the di and also the a tag.

not a good idea! <- Sorry, i thought there are two ids with the same name

this was working for me. But it's possible that i did not understand your question correctly

  $('#drink1').clone().attr('id','drink2').appendTo('#drinks')

How about something like this:

var id = $(this).attr('id');
var targetDiv = $('.' + id);

Int his instance target div will be the divs with the class name matching that ID

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top