jQuery 备忘录

2017-09-14  本文已影响0人  AsianDuckKing
选区_028.png
var obj = $('#item1');
var dom = obj.get(0)

The above code will give you the first DOM element

var element = $('[type=password]'); // Search by property (Using ^ and $ can find the first and last one)
ul.append(function (index, html) {
    return '<li><span>Language - ' + index + '</span></li>';
});

If you want to modify an element in the same level, you can use the after() and before() method.

 $('#testForm).on('submit', function () {
            alert('submit!');
        });

You should use the following:

$(document).on('ready', function () {
            $('#testForm).on('submit', function () {
                alert('submit!');
            });
        });

And the above code can be simplified as:
$(function(){})
which is very popular in the industrial code.

var div = $('#test-animate');
div.animate({
    opacity: 0.25,
    width: '256px',
    height: '256px'
}, 3000, function () {
    console.log('动画已结束');
    // 恢复至初始状态:
    $(this).css('opacity', '1.0').css('width', '128px').css('height', '128px');
});
var div = $('#test-animates');
// 动画效果:slideDown - 暂停 - 放大 - 暂停 - 缩小
div.slideDown(2000)
   .delay(1000)
   .animate({
       width: '256px',
       height: '256px'
   }, 2000)
   .delay(1000)
   .animate({
       width: '128px',
       height: '128px'
   }, 2000);
}
</script>

Alternative choice to animate()(maybe better choice): CSS3's transition

$.fn.highlight = function (options) {
    // 合并默认值和用户设定值:
    var opts = $.extend({}, $.fn.highlight.defaults, options);
    this.css('backgroundColor', opts.backgroundColor).css('color', opts.color);
    return this;
}

// 设定默认值:
$.fn.highlight.defaults = {
    color: '#d85030',
    backgroundColor: '#fff8de'
}
$.fn.external = function () {
    // return返回的each()返回结果,支持链式调用:
    return this.filter('a').each(function () {
        // 注意: each()内部的回调函数的this绑定为DOM本身!
        var a = $(this);
        var url = a.attr('href');
        if (url && (url.indexOf('http://')===0 || url.indexOf('https://')===0)) {
            a.attr('href', '#0')
             .removeAttr('target')
             .append(' <i class="uk-icon-external-link"></i>')
             .click(function () {
                if(confirm('你确定要前往' + url + '?')) {
                    window.open(url);
                }
            });
        }
    });
}
上一篇下一篇

猜你喜欢

热点阅读