旧笔记归档

filter 和 find 的区别

现在有一个页面,里面 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>

结论

  • find() 会在 div 元素内寻找 class 为 rain 的元素,是对它的子集操作

  • filter() 则是筛选 div 的 class 为 rain 的元素,是对它自身集合元素筛选


submit a form in ajax success callback-AJAX 成功时回调函数中提交 Form

首先 "target": "_blank" 肯定可以打开新页面

重点在于想要添加 async: false

  $.ajax({
      url: "……",
      method: "post",
      data:{ ……},
      async: false,
      success:function(res){
          form.attr({"action": newurl, "target": "_blank"});
          form[0].submit();
      }
  });

API

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().


JQuery-Error: Form submission causing 'Maximum call stack size exceeded'

Desc

使用form.submit();的时候没有报错但是无限循环执行 过了几秒后报错

'Maximum call stack size exceeded'

Solution

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'.


AJAX 相关

AJAX 传递额外参数-pass extra arg when ajax finished/succeed

(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 进去


.each()的使用

$('img[id^=CF_HELPTEXT_]').each(function(index, value){ 
   value.click(); 
});

将 Jquery obj 里面的所有元素都点击一遍


获取数据

substr 获得子字符串

stringObject.substr(start,length)
参数描述
start
必需。要抽取的子串的起始下标。必须是数值。如果是负数,那么该参数声明从字符串的尾部开始算起的位置。也就是说,-1 指字符串中最后一个字符,-2 指倒数第二个字符,以此类推。
length
可选。子串中的字符数。必须是数值。如果省略了该参数,那么返回从 stringObject 的开始位置到结尾的字串。

得到选中的 option 的内容

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();

控件相关

select

添加 option

$('#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 
    }));
});

disable select

$("#"+arrFields[i]).prop('disabled', true);
$("#"+arrFields[i]).prop('disabled', false);

删除 select 里面所有 option

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()不能一起执行 分成两句后解决问题


Checkbox

勾选所有 Checkbox

$('input:checkbox').prop("checked", true);

注意使用的是prop()

得到 checkbox 的值

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(',')
 
 

选中某 Checkbox 的同时取消选择其他所有 jQuery: Uncheck other checkbox on one checked

$('input.chkbox').on('change', function() {
  if(this.checked) $('input.chkbox').not(this).prop('checked', false); 
});

判断是否被选中

JS:

document.getElementById('viewDept').checked

JQuery:

$('id').is(':checked')

注意这里使用了伪类


Toggle for editable of inputs

$('#el').prop('disabled', function(i, v) { return !v; });
$("input[type='checkbox']").is(':checked')

返回结果:选中=true,未选中=false


获取 Iframe 里面的元素 和 Jquery 操作 CSS&style

使用 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();//清空下拉框.

JQuery 动态添加表单

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 效率比较高并且兼容性强

获取 Jquery 对象数组中的所有文字

arr = $('#mw-content-text .navbox-list .navbox-list a').map(function(i, el) {
    console.log( $(el).text());
}).get();

Jquery 对象的属性转为数组 Query select attributes into an array

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 文件上传

注意关于附件,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");
    });
 
});
 

关于 attachEvent 报错

Error Msg

In IE 11: Object doesn't support property or method 'attachEvent'

In Chrome: window.attachEvent is not a function

Desc

attachEvent is a deprecated function used in older versions of Internet Explorer. For modern browsers use this instead.

el.addEventListener(evt,func,false);

Solution1

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!');
});

Solution2

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();
});

.trigger()

Desc

Execute all handlers and behaviors attached to the matched elements for the given event type.

Syntax

.trigger( event [, extraParameters ] )

实际上就是触发已经有的 event

Examples

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"
});

.ready()

There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8

Desc

Specify a function to execute when the DOM is fully loaded.

Syntax

All three of the following syntaxes are equivalent:

$( document ).ready( handler )

$().ready( handler ) this is not recommended)

$( handler )

Arguments

  • handler
    • Type: Function()
    • A function to execute after the DOM is ready.

Example

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.
});

JQuery&AJAX-Get/Post

示例

// 请求 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

参数

AttrExp
url必需。规定将请求发送的哪个 URL。
data可选。规定连同请求发送到服务器的数据。
success可选。规定当请求成功时运行的函数。

额外的参数:
- success(response,status,xhr)
- response - 包含来自请求的结果数据
- status - 包含请求的状态
- xhr - 包含 XMLHttpRequest 对象
dataType可选。规定预计的服务器响应的数据类型。默认地,jQuery 将智能判断。
可能的类型:
- "xml"
- "html"
- "text"
- "script"
- "json"
- "jsonp"

JQuery-AJAX-Post-Json

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 );
    }
})

.bind()

Desc

Attach a handler to an event for the elements.

Syntax

$(selector).bind(event,data,function)

Arguments

  • event
    • 必需。规定添加到元素的一个或多个事件。
    • 由空格分隔多个事件。必须是有效的事件。
  • data
    • 可选。规定传递到函数的额外数据。
  • function
    • 必需。规定当事件发生时运行的函数。

Example

给一个 Button 绑定点击事件

$("button").bind("click",function(){
  $("p").slideToggle();
});

.on()

Syntax

$(selector).on( events [, selector ] [, data ], handler )

如果后面的 Handler 不是一个 function 变量的话,就必须写成一个匿名函数

Example

$( "#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" ] );

JQuery Simple Merge

var myArray = [1,2,3,4,5,6];
console.log(myArray.slice(-1)[0])

扩展 Jquery 的 $ 方法

!function(a){
    a.extend({
        xxx: function(arg1, arg2){
            ……
        }
    })
}(jQuery)

实际上是将 Jquery 传进去并执行了 extend 方法, 之后可以通过$.xxx(arg1, arg2)进行调用

Example

  • 目的是扩展 JQuery, 以下对 jQuery 扩展了一个方法.
    • $ 或者 jQuery 仅仅是一个 constructor, 每一个变量都是它的实例.
    • 另外 $.fn 其实是 $.prototype 的别名, 给 prototype 添加方法即是给 jQuery 扩展方法
    • 使用的时候只需要 $('xxx').tipTip(args) 即可.
(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);

JS triggering json file download

有几个方法, 测试有效的是 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