旧笔记归档
现在有一个页面,里面 HTML 代码为:
<div >
<p class="rain">测试 1</p>
</div>
<div class="rain">
<p>测试 2</p>
</div>
如果我们使用find()
方法:
var result = $("div").find(".rain");
alert(result.html() ) ;
结果:
测试 1
如果使用filter()方法:
var result = $("div").filter(".rain");
alert(result .html() );
结果:
<p>测试 2</p>
首先 "target": "_blank"
肯定可以打开新页面
重点在于想要添加 async: false
$.ajax({
url: "……",
method: "post",
data:{ ……},
async: false,
success:function(res){
form.attr({"action": newurl, "target": "_blank"});
form[0].submit();
}
});
async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
使用form.submit();
的时候没有报错但是无限循环执行 过了几秒后报错
'Maximum call stack size exceeded'
http://stackoverflow.com/questions/31379409/form-submission-causing-maximum-call-stack-size-exceeded
Replace $('#fReviewMe').submit();
with:
$('#fReviewMe')[0].submit();
calling DOM node method submit
to avoid submit jQuery handler 'loop'.
(function(v){
$.ajax({
url: 'index.cfm?reg_profile'
})
.done(function(data) {
// data
// you can get v here
})
})(btn)
试了几个方法, 比如将参数放到.done()
里面作为第二个参数等等都不行, 只需要建立一个闭包即可实现
.done()
可以接受三个参数
function onMyUrlLoaded(data, textStatus, jqXHR) { /* function code */ };
但是无法通过第四个参数来进行传值
另一种办法:
done(function(magic) {
return process(magic, 42);
});
或者
callWithMagic(magic => processMagic(magic, 42));
这样可以传一个 42 进去
$('img[id^=CF_HELPTEXT_]').each(function(index, value){
value.click();
});
将 Jquery obj 里面的所有元素都点击一遍
stringObject.substr(start,length)
参数 | 描述 |
---|---|
start | 必需。要抽取的子串的起始下标。必须是数值。如果是负数,那么该参数声明从字符串的尾部开始算起的位置。也就是说,-1 指字符串中最后一个字符,-2 指倒数第二个字符,以此类推。 |
length | 可选。子串中的字符数。必须是数值。如果省略了该参数,那么返回从 stringObject 的开始位置到结尾的字串。 |
get the text value of a selected option
$( "#myselect" ).val();
If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
$( "#myselect option:selected" ).text();
$('#mySelect').append($('<option>', {
value: 1,
text: 'My option'
}));
If you're adding options from a collection of items, you can do the following:
$.each(items, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.text
}));
});
$("#"+arrFields[i]).prop('disabled', true);
$("#"+arrFields[i]).prop('disabled', false);
remove all the options of a select box and then add one option and select it
$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;
注意原因不明多个 remove()不能一起执行 分成两句后解决问题
$('input:checkbox').prop("checked", true);
注意使用的是prop()
JS 方法
document.getElementById('viewDept').checked
Jquery 方法
$('id').val()
得到多个值并用逗号分割:
var state_array=new Array();
$('input[type=checkbox][name=state]:checked').each(function(index, el) {
state_array.push($(this).val());
});
var states = state_array.join(',')
$('input.chkbox').on('change', function() {
if(this.checked) $('input.chkbox').not(this).prop('checked', false);
});
JS:
document.getElementById('viewDept').checked
JQuery:
$('id').is(':checked')
注意这里使用了伪类
$('#el').prop('disabled', function(i, v) { return !v; });
$("input[type='checkbox']").is(':checked')
返回结果:选中=true,未选中=false
使用 Jquery 直接获取 Iframe 里面的元素是不行的 需要多一层操作
$("#portalFrameID").contents().find(".smelter-alert").css("background-color","blue");
获取表单里各种值
获取值:
文本框,文本区域:$("#txt").attr("value");
多选框 checkbox:$("#checkbox_id").attr("value");
单选组 radio: $("input[@type=radio][@checked]").val();
下拉框 select: $('#sel').val();
控制表单元素:
文本框,文本区域:$("#txt").attr("value",'');//清空内容
$("#txt").attr("value",'11');//填充内容
多选框 checkbox: $("#chk1").attr("checked",'');//不打勾
$("#chk2").attr("checked",true);//打勾
if($("#chk1").attr('checked')==undefined) //判断是否已经打勾
单选组 radio: $("input[@type=radio]").attr("checked",'2');//设置 value=2 的项目为当前选中项
下拉框 select: $("#sel").attr("value",'-sel3');//设置 value=-sel3 的项目为当前选中项
$("<option value='1'>1111</option><option value='2'>2222</option>").appendTo("#sel")//添加下拉框的 option
$("#sel").empty();//清空下拉框.
var $form = $('<form method="post" action="tib.cfm?ajaxModal"></form>');
$form.append('<input name="index" type="hidden" value="'+$(this).data('metaresultid')+'" />')
.append('<input name="type" type="hidden" value="excel" />')
.appendTo('body')
.submit();
return false;
使用 JQuery 效率比较高并且兼容性强
arr = $('#mw-content-text .navbox-list .navbox-list a').map(function(i, el) {
console.log( $(el).text());
}).get();
var myVals = [];
$('li','ul').each(function(){
myVals.push($(this).attr('value'));
});
可以对单个 Elem 进行滚动,或者对 window 进行滚动 可以滚动到对应 y 轴位置,数字作为参数,也可以滚动到对应 elem
$('#BoxModalContent').scrollTop('#BoxModalContent')
使用.on()
bind 事件,使用.unBind()
取消 bind 事件
注意事件不会被覆盖,因此如果希望加载另一个同名事件则需要先取消加载然后重新 bind
$('#modalContinue').unbind('click').on('click', function(event) {
/* do sth*/
});
注意关于附件,AJAX 仅仅能上传,下载的话需要打开一个新页面。
直接用 form.serialize()
对于文件选择的 input 无效。 因此只需要使用 FormData 这个 Object 即可解决问题
$('#upload').on('click', function(event) {
var data = new FormData($("[name=excelUploadForm]")[0]);
$.ajax({
url: 'sir_distExcelUpload.cfm?type=read',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: data
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
In IE 11: Object doesn't support property or method 'attachEvent'
In Chrome: window.attachEvent is not a function
attachEvent is a deprecated function used in older versions of Internet Explorer. For modern browsers use this instead.
el.addEventListener(evt,func,false);
You could also create a function which checks which function to use
function addListener(el, event, func){
if (el.addEventListener) {
el.addEventListener(event, func, false);
}
else {
el.attachEvent("on"+event, func);
}
}
Then you can attach your event by doing this:
var element = document.getElementById('myElement');
addListener(element, 'click', function(){
alert('You have clicked!');
});
If you are unable to do this then perhaps a polyfill will work instead. Try to insert this somewhere:
if(!document.attachEvent){
Object.prototype.attachEvent=function(event,func){
this.addEventListener(event.split('on')[1], func);
}
}
触发实例:
$("button#demo").click()
上面的例子将触发 id="demo" 的 button 元素的 click 事件。
绑定实例:
$("button#demo").click(function(){$("img").hide()})
$('ul.scopeSelector img.plusminus').click(function(){
//some code
//$(this).next().next().toggle();
});
Execute all handlers and behaviors attached to the matched elements for the given event type.
.trigger( event [, extraParameters ] )
实际上就是触发已经有的 event
To pass arbitrary data to an event:
$( "p" )
.click(function( event, a, b ) {
// When a normal click fires, a and b are undefined
// for a trigger like below a refers to "foo" and b refers to "bar"
})
.trigger( "click", [ "foo", "bar" ] );
Alternative way to pass data through an event object:
$( "body" ).trigger({
type:"logged",
user:"foo",
pass:"bar"
});
There is also $(document).on( "ready", handler )
, deprecated as of jQuery 1.8
Specify a function to execute when the DOM is fully loaded.
All three of the following syntaxes are equivalent:
$( document ).ready( handler )
$().ready( handler ) this is not recommended)
$( handler )
The .ready() method is typically used with an anonymous function:
$( document ).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
// 请求 test.php 网页,传送 2 个参数,忽略返回值:
$.get("test.php", { name: "John", time: "2pm" } );
// 显示 test.php 返回值(HTML 或 XML,取决于返回值):
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
$(document).ready(function(){
$("#jquery").click(function(){
$.get("result.cfm?name="+$("#INPUTLOOKUP").val(),function(result){
$("#result").html(result);
});
});
});
对应的目标处理参考:
$.ajax({
url:"?getdatasubset",
method:"post",
data:{
dids:dids,
cols:columns,
colnames:colnames,
ordr:ordr,
count:count==undefined?10:count
},
success:function(res){$('#BoxModalContent').html(res);},
error:function(xhr,etype,emsg){$('#BoxModalContent').html(emsg);}
});
data 中带有多参数的示例
$.ajax({
url:"?getdatasubset_XML",
method:"post",
data:{
data:'<data>' + xmlStr + '</data>',
subtitle:subtitle,
showsum:showsum
},
success:function(res){$('#BoxModalContent').html(res);},
error:function(xhr,etype,emsg){$('#BoxModalContent').html(emsg);}
});
get() 方法通过远程 HTTP GET 请求载入信息。 这是一个简单的 GET 请求功能以取代复杂 .ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 .ajax。
Attr | Exp |
---|---|
url | 必需。规定将请求发送的哪个 URL。 |
data | 可选。规定连同请求发送到服务器的数据。 |
success | 可选。规定当请求成功时运行的函数。额外的参数:- success(response,status,xhr)- response - 包含来自请求的结果数据- status - 包含请求的状态- xhr - 包含 XMLHttpRequest 对象 |
dataType | 可选。规定预计的服务器响应的数据类型。默认地,jQuery 将智能判断。可能的类型:- "xml"- "html"- "text" - "script" - "json" - "jsonp" |
var json = {a:1,b:2}
var c = 1;
$.ajax({
url: 'getFormFile.cfm',
type:'POST',
data: { "a": JSON.stringify(json)},
success: function(data){
$('#getDate').html(data);
},
error:function( jqXHR, textStatus, errorThrown ){
alert( "Error" + errorThrown );
}
})
Attach a handler to an event for the elements.
$(selector).bind(event,data,function)
给一个 Button 绑定点击事件
$("button").bind("click",function(){
$("p").slideToggle();
});
$(selector).on( events [, selector ] [, data ], handler )
如果后面的 Handler 不是一个 function 变量的话,就必须写成一个匿名函数
$( "#dataTable tbody tr" ).on( "click", function() {
console.log( $( this ).text() );
});
Pass data to the event handler, which is specified here by name:
function myHandler( event ) {
alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );
Cancel a form submit action and prevent the event from bubbling up by returning false:
$( "form" ).on( "submit", false );
Stop submit events from bubbling without preventing form submit, using .stopPropagation().
$( "form" ).on( "submit", function( event ) {
event.stopPropagation();
});
Use the the second argument of .trigger()
to pass an array of data to the event handler
$( "div" ).on( "click", function( event, salutation, name ) {
alert( salutation + ", " + name );
});
$( "div" ).trigger( "click", [ "Goodbye", "Jim" ] );
var myArray = [1,2,3,4,5,6];
console.log(myArray.slice(-1)[0])
!function(a){
a.extend({
xxx: function(arg1, arg2){
……
}
})
}(jQuery)
实际上是将 Jquery 传进去并执行了 extend 方法, 之后可以通过$.xxx(arg1, arg2)
进行调用
(function ($) {
$.fn.tipTip = function (options) {
var defaults = {
arg1: "123",
arg2: false,
};
// merge arguments with default arguments
var opts = $.extend(defaults, options);
return this.each(function (e) {
active_tiptip(opts);
})
function active_tiptip(opts) { }
function deactive_tiptip(opts) { }
}
}
)(jQuery);
有几个方法, 测试有效的是 Blob 下载:
saveFile: function() {
const data = JSON.stringify(this.arr)
const blob = new Blob([data], {type: 'text/plain'})
const e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = "test.json";
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
}
其他方法查看这篇文章: https://stackoverflow.com/questions/48611671/vue-js-write-json-object-to-local-file