JS中字符串与数字类型数据的拼接

我想用ajax来实现购物商城中对于默认地址的切换,而不需要对界面进行重新加载,但是在操作中遇到了一些问题,主要就是字符串与数字类型数据拼接的时候遇到了bug。
以下为CSS代码:

       {% for item in list %}
            <div class="site_con">
            <dl>
                <dd><a href="#">{{ item.address }} {{ item.detail }} ({{ item.realname }} 收) {{ item.phone }}</a></dd>
                <dd>
                    <div>
                        {% if item.def_address %}
                        <input type="checkbox" checked="checked" style="vertical-align:middle;"
                            onclick="defAddress({{ item.id }})" id="{{ forloop.counter}}"/>
                        {% else %}
                        <input type="checkbox"  style="vertical-align:middle;"
                            onclick="defAddress({{ item.id }})" id="{{ forloop.counter }}"/>
                        {% endif %}
                        <span style="vertical-align:middle;" >默认地址</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                        <a href="/user/address_edit/?id={{ item.id }}" style="vertical-align:middle;" >编辑</a>&nbsp;&nbsp;&nbsp;
                        <a href="#" style="vertical-align:middle;"  onclick="deleteAddress({{ item.id }})">删除</a>
                    </div>
                </dd>
            </dl>
            </div>

        {% endfor %}

JS代码如下:

    function defAddress(currentId) {

            $.get('/user/address_default/',{'currentId':currentId},function (data) {

                $.each(data.address_list,function (index, item) {
                    if(item.def_address==1){

                        $('#'+(index+1)+'').prop('checked',true)

                    }else {
                            $('#'+(index+1)+'').prop('checked',false)
                    }
                })
            })
}

那么在JS代码中,id选择器是一个字符#和数字变量index以及数字1拼接起来的,在js中,字符串得与数字的拼接不需要将数字转换成字符串,JS会自动将数字转换成字符串,但是,不能这样写:

  $('#'+index+1+'').prop('checked',true)

一定记住,因为拼接出来的为#11,而我们要的是#2,所以要写成:

  $('#'+(index+1)+'').prop('checked',true)

这一点一定要记住,而且要细心!

猜你喜欢

转载自blog.csdn.net/weixin_40612082/article/details/80910248
今日推荐