Создать новый элемент и задать ему параметров
$('<a></a>').html(obj).attr('href', obj)
Работаем со значением полей у форм
<script src="http://code.jquery.com/jquery.min.js"></script>
<input type='text' value='Def value'>
<script>
var i = $('input')
console.log(i.val())
i.val('')
console.log(i.val())
i.val('New value')
console.log(i.val())
</script>
Def value
New value
Проверяем - отмечены ли чекбоксы
<script src="http://code.jquery.com/jquery.min.js"></script>
<input type='checkbox' id='checkbox-1' checked>
<input type='checkbox' id='checkbox-2' checked>
<input type='checkbox' id='checkbox-3'>
<input type='checkbox' id='checkbox-4'>
<script>
console.log($('#checkbox-1').attr('checked'))
console.log($('#checkbox-2').is(':checked'))
console.log($('#checkbox-3').attr('checked'))
console.log($('#checkbox-4').is(':checked'))
</script>
checked
true
undefined
false
Устанавливаем и убираем значение у чекбоксов
<script src="http://code.jquery.com/jquery.min.js"></script>
<input type='checkbox'>
<script>
var i = $('input')
i.attr('checked', true) //check
i.attr('checked', false) //uncheck
i.attr('checked', 'checked') //check
i.removeAttr('checked') //uncheck
</script>
Получить случайный элемент
<script src="http://code.jquery.com/jquery.min.js"></script>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
<script>
jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"], {
random: function(a, i, m, r){
if (i == 0)
jQuery.jQueryRandom = Math.floor(Math.random() * r.length)
return i == jQuery.jQueryRandom
}
})
$(function() {
alert($("li:random").text())
})
</script>
Найти родительский блок с определённым классом.
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
function find_block(){
alert($(this).parents('.block').html())
}
</script>
<div class='block'>
<p>
<span>
<a href='#' onclick='find_block.call(this)'>click!</a>
</span>
</p>
</div>
Отправить форму при нажатии на ссылку
<script src="http://code.jquery.com/jquery.min.js"></script>
<form onsubmit='alert("Catched!"); return false'>
<a href='#' onclick='$(this).parents("form").submit()'>Submit.</a>
</form>
Подключить самый новый jQuery.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
Сбрасываем форму
$('#'+id).each(function(){
this.reset();
});
Убрать пробельные символы из начала и конца строки
var str = " lots of spaces before and after ";
console.log('"'+$.trim(str)+'"');
"lots of spaces before and after"
Сериализовать форму.
$('form').serializeArray();
Получаем координаты курсора мыши при его движении
$('body').mousemove(function(e){
console.log(e.clientX, e.clientY);
});
Источники:
- 2 - api.jquery.com
- 3 - jquery-howto.blogspot.com
- 4 - docs.jquery.com
- 5 - blog.mastykarz.nl
- 9 - simple.procoding.net
- 10 - api.jquery.com
- 11 - api.jquery.com