2

I made a small function to calculate width along with margin of li but it is giving me error.

<head>

<style>

.bill ul{ list-style:none}

.bill ul li{ float:left; width:94px; margin-right:18px}

.bill ul li:last-child { margin-right:0}

</style>

<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">

$(function (){

    $('.bill').find('li').each(function (){
            var jn += parseInt($(this).css('margin-right')) + $(this).width();
        })


        alert(jn)


    })


</script>

</head>

<body>

<div class="bill">
<ul>
<li>aaa</li>
<li>aaa</li>
<li>aaa</li>
<li>aaa</li>
<li>aaa</li>

</ul>
</div>

</body>
1
  • it is giving me syntax error "var jn += parseInt($(this).css('margin-right')) + $(this).width();" here Commented Aug 16, 2012 at 8:55

2 Answers 2

3

You're declaring the jn variable using the var keyword inside the anonymous function passed to .each(), meaning that the variable will be scoped inside of that function and not exist outside of it.

Trying to call alert(jn) will likely result in undefined being alerted, because the jn variable isn't visible in the scope of that statement.

In addition, declaring a variable and using the += operator is invalid syntax. The variable has to exist in order for you to add to its value. Try the following:

$(function (){
    var jn = 0;

    $('.bill').find('li').each(function (){
        jn += parseInt($(this).css('margin-right')) + $(this).width();
    });

    alert(jn);
});
Sign up to request clarification or add additional context in comments.

Comments

0

better way to do this is to use jQuery position() http://api.jquery.com/position/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.