工作中用到的一些代码,觉得有点用,怕忘记了,记下来
javascript获取当前位置
var a = document.location.href.split("?")[0];
alert(a); alert(location.href);看明白这段代码,就能理解闭包了
<script type="text/javascript" >
function createFunctions() { var result = new Array(); for(var i = 0; i < 10; i++) { result[i] = function() { return i; }; } return result; }var funcs = createFunctions();
for(var i = 0; i < funcs.length; i++) { document.write(funcs[i]() + "<br/>");}
function createFunctions2() {
var result = []; for(var i = 0; i < 10; i++) { result[i] = function(num) { return function() { return num; }; }(i); } return result; }var funcs = createFunctions2();
for(var i = 0; i < funcs.length; i++) { document.write(funcs[i]() + "<br/>");}
</script>
setTimeout()可以直接运行javascript代码:
<script type="text/javascript">
var graph = {};
graph.donald = function() { alert("hello Kitty"); }; if (graph.donald) { graph.donald(); } setTimeout("alert('setTimeout can be used by this way')", 1000); </script>
javaScript提供的json对象与String对象之间的转换方法:
<script>
//String 转换成json
var jsonObj = JSON.parse('{"helloKitty":"donald duck"}');//json 转换成String
var str = JSON.stringify(jsonObj); </script>
javaScript判断对象是否为空的方法:
function isNull(arg) {
if (arg == null || (typeof (arg)) == 'object' && !arg) { return true; }return false;
}
jQuery的事件处理demo
<!DOCTYPE html>
<html><head><style>p { color: red;}span {
color: blue;}</style><script src="http://code.jquery.com/jquery-1.7rc2.js"></script></head><body> <p>Has an attached custom event.</p> <button>Trigger custom event</button> <span style="display: none;"></span> <script> $("p").on("myCustomEvent", function(e, myName, myValue) { $(this).text(myName + ", hi there!" + myValue); $("span").stop().css("opacity", 1).text("myName = " + myName + "\n" + "myValue = " + myValue).fadeIn(30).fadeOut(1000); }); $("button").click(function() { $("p").trigger("myCustomEvent", [ "John", "donald duck" ]); }); </script></body>
</html>