javascript 使用ref在vuejs中获取元素

使用ref在vuejs中获取元素,因此可以使用dom方法

ref
// in template

<article ref="imageContainer"> whatever </article>


// in logic

this.$refs.imageContainer

javascript FizzBu​​zz

FizzBu​​zz

reverseMultiples.js
/** 
 * Reverse 3 Multiples
 * Instruction: Write a program that prints out, in reverse order, 
 * every multiple of 3 between 1 and 200.
 *
 * Reationale: Doing it in normal order it easy: multiply the loop index by 3 
 * until you reach a number that exceeds 200, then quit. You don't have to worry
 * about how many iterations to terminate after, you just keep going until you
 * reach the first value that's too high. But going backwards, you have to know
 * where to start. Some might realize intuitively that 198 (3 * 66) is the
 * highest multiple of 3, and as such, hard-code 66 into the loop. Others might
 * use a mathematical operation (integer division or a floor() on a floating
 * point division of 200 and 3) to figure out that number, and in doing so, 
 * provide something more generically applicable.
**/
fizzbuzz.js
/** 
 * FizzBuzz 
 * Instruction: Write a program that prints the numbers from 1 to 100. 
 * But for multiples of three print "Fizz" instead of the number and for the 
 * multiples of five print "Buzz". For numbers which are multiples of both three 
 * and five print "FizzBuzz".
**/

// Common dynamic implementation, vanilla:
function fizzbuzz(start = 0, end = 100, dict = {3: 'Fizz', 5: 'Buzz'}) {
  for (let i = start; i <= end; i++) {
    let word = '';
    for (const divider in dict) {
      if (i % divider === 0) {
        word += dict[divider];
      }
    }
    console.log(word || i);
  }
}

// Minimal static implementation, vanilla:
fb = () => for(i=0;i++<100;console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i));

// Minimal dynamic implementation, vanilla:
fb = (start = 0, end = 100, dict = {3: 'Fizz', 5: 'Buzz'}) => for(i=start;i++<end;console.log(Object.keys(dict).map(k=>i%k?'':dict[k]).join('')||i));

// Minimal Dynamic implementation with Lodash, single print:
fb = (start = 0, end = 100, dict = {3: 'Fizz', 5: 'Buzz'}) => console.log(_(_.range(start, end + 1)).map(i => _(dict).keys().map(k => i % k === 0 ? dict[k] : null).compact().join('') || i).join('\n'));

// https://blog.codinghorror.com/why-cant-programmers-program/

javascript reg_add_middle_start

reg_add_middle_start.js
var reg = /(^.{10})(?:.{4})(.*)/;
var str = 'abcdefgABCDEFGabcdefgABCDEFGabcd';
var newStr = str.replace(reg, '$1****$2');
console.log(newStr);
'abcdefgABC****abcdefgABCDEFGabcd'

javascript Javascript警报

如何创建警报

Alert.js
alert('Hello Captain America');

javascript nodejs路由控制是否登录nuxt.js框架

nodejs根据是否登录进行路由跳转控制nuxt.js框架

check-login.js

export default function ({ isServer, store, req, redirect }) {
  if (isServer && !req) return
  if (isServer) {
    let noNeedLoginPages = ['login', 'register', 'forgetPassword', 'clause']
    let url = req.url.substr(1)
    let user = req.session.user
    // let user=store.state.user.user // 刷新一下,store就没有了,所以不能用store
    console.log(user, 99)
    if (!user) {
      if (!noNeedLoginPages.includes(url)) {
        redirect('/login')
        return undefined // return 一定要加上,否则不能跳转
      }
    }
    // else {
    //   store.commit('SET_USER', user)
    //   return undefined
    // }
  }
}

nodejs方法
app.use(function (req, res, next) {
  
  if (!req.session.user) {
    if (req.url === '/login' || req.url === '/register') {
      next()  
    } else {
      res.redirect('/login')
    }
  } else if (req.session.user) {
    next()
  }
})

javascript JQuery Snippets

JQuery Snippets

Normal

// GET INNER HTML OF A CLASS
$('.a')[0].innerHTML;
$('.a')[1].innerHTML;
Text Box
//Text Change Event
$('#selector').on('input', function () {
    alert($('#selector').val());
});

//Trigger Text Change
$('#searchTable_' + currentCaller).trigger('change');

//Color Change Example
$(function(){
    $("input").focus(function(){
        $(this).css("background-color","#cccccc");
    });
   
    $("input").blur(function(){
        $(this).css("background-color","#ffffff");
    });
});


// NUMERIC VALIDATION
// SOURCE: https://stackoverflow.com/a/995193
 $('.txtCampaignBudget').keydown(function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
        // Allow: Ctrl+A, Command+A
        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
        // Allow: home, end, left, right, down, up
        (e.keyCode >= 35 && e.keyCode <= 40)) {
        // let it happen, don't do anything
        return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }

});

Data

//Get Value
$(this).attr("data-id") // will return the string "123"
or 
.data() (if you use newer jQuery >= 1.4.3)

$(this).data("id") // will return the number 123


<div id="mydiv" data-myval="10"></div>

//Getter
var a = $('#mydiv').data('myval');

//Setter
$('#mydiv').data('myval',20);

Checkbox

//Set Checkbox checked
$('.cbFacebook').prop('checked', true);

//Get Checkbox checked
$('.cbFacebook').prop('checked');

// Get Checkbox checked by Name
$("input[name='SomeName']").prop('checked')


//Check if is checked
$('.cbFacebook').is(':checked');

//Checked Change Event
$(".checkbox").change(function () {
    if (this.checked) {
        //Do stuff
    }
});

//Get Value
$( "input:checkbox:checked" ).val();


var len = $("#divHelpContainer input[name='cbxKeywords']:checked").length;
Select
// Multiple Select Length
var count = $("#divBusinessTypeComponents :selected").length;

// Selected Value
var value = $('#slcSiteCategory option:selected').val();

// Select First Option
$("#target").val($("#target option:first").val());

// Selection Change Event
$('#slcSiteSector').on("change", function () {
});

// Get Array of values
var selectedBusinessTypes = [];
$("#divBusinessTypeComponents :selected").each(function () {
          selectedBusinessTypes.push(this.value);
});

// Get Select option data attribute
$('.sclChooseLocation').find(':selected').data('code')
Jquery Validation - Drop Down
$('#ddlSomething').rules('add', {
    required: {
        depends: function (element) {
            if ($(this).find(":selected").val() === '') {
                return true;
            }
            return false;
        }
    },
    messages: {
        required: "You have not choosen any thing."
    }
});


javascript canvasRender支持标签避让测试代码

参考inmap四分位标签避让算法(https://github.com/TalkingData/inmap/blob/master/src/worker/helper/Label.js),基于createjs在canvasRender上实现标签避让或隐藏功能。<br/>测试代码,未考虑不同位置标签样式的处理,未对标签按照坐标进行排序。

label.js
if(entry.label&&entry.label.text&&entry.label.type=='box'){
                var style=L.extend({
                    fillColor:'white',//填充色
                    fillOpacity:1,//填充透明度
                    color:'blue',//边框颜色
                    opacity:1,//边框透明度
                    width:2,//边框宽度
                    textColor:'black',//文本颜色
                    textFont:'bold 14px Microsoft YaHei',//文本字体
                    boxHeight:24,//box高度(宽度自适应)
                    hideBox:false,//是否隐藏背景box
                    padding:10,//文本左右离box的距离,单位:像素
                    textAlign:'center',//对齐方式:center文本中心点 left文本左侧,right文本右侧  参考canvas api中的textAlign
                    offset:[0,0]//偏移量,单位:像素
                },options.labelStyle,entry.label.style);
                var txt = new createjs.Text();
                txt.text=entry.label.text;
                txt.color=style.textColor
                txt.font=style.textFont;
                txt.textAlign=style.textAlign;
                txt.textBaseline='middle';
                var x = point.x;
                var y = point.y;
                var bound=txt.getBounds();
                var position = 0;
                function getBounds(bd) {
                    var txtBound = txt.getBounds();
                    var width = txtBound.width;
                    var height = txtBound.height;
                    if (!style.hideBox) {
                        width = txtBound.width + style.padding + style.width * 2;
                        height = 24
                    }
                    switch(position) {
                        case 0:
                            x = point.x;
                            y = point.y;
                            break;
                        case 1:
                            x = point.x - width / 2;
                            y = point.y - height;
                            break;
                        case 2:
                            x = point.x - width / 2;
                            y = point.y + height;
                            break;
                        case 3:
                            x = point.x - width;
                            y = point.y;
                            break;
                    }
                    return bd.setValues(x, y, width, height);
                }
                var show = true;
                var meet = false;
                do {
                    bound = getBounds(bound);
                    meet = false;
                    for (var l = 0; l < labels.length; l++) {
                        var label = labels[l];
                        if (!label || label.show === false) {
                            continue;
                        }
                        if (label.bound.intersects(bound)) {
                            meet = true;
                            position++;
                            if (position > 3) {
                                show = false;
                                meet = false;
                            }
                            break;
                        }
                    }
                } while(meet)
                labels.push({
                    x: x,
                    y: y,
                    data: entry.label,
                    style: style,
                    bound: bound,
                    show: show
                })
                if (!show) {
                    continue;
                }
                //console.info(bound);
                var container = new createjs.Container();
                if(!style.hideBox){
                    var width=bound.width;
                    var topLeft={};
                    if(style.textAlign=='center'){
                        topLeft.x=x-width/2;
                        topLeft.y=y-style.boxHeight/2;
                    }else if(style.textAlign=='left'){
                        topLeft.x=x-style.padding/2;
                        topLeft.y=y-style.boxHeight/2;
                    }else if(style.textAlign=='right'){
                        topLeft.x=x-width+style.padding/2;
                        topLeft.y=y-style.boxHeight/2;
                    }
                    topLeft.x+=style.offset[0];
                    topLeft.y+=style.offset[1];

                    var border = new createjs.Shape();
                    border.alpha=style.opacity;
                    border.graphics.setStrokeStyle(style.width).beginStroke(style.color).drawRoundRect(topLeft.x,topLeft.y,width,style.boxHeight,style.boxHeight/4);
                    this.stage.addChild(border);
                    var box=new createjs.Shape();
                    box.alpha=style.fillOpacity;
                    box.graphics.beginFill(style.fillColor).drawRoundRect(topLeft.x,topLeft.y,width,style.boxHeight,style.boxHeight/4);
                    box.cursor='pointer';
                    box.data=_data[id];
                    box.dataGroupId=id.split('#')[0];
                    this.stage.addChild(box);
                }
                txt.x = x+style.offset[0];
                txt.y = y+style.offset[1];
                txt.data=_data[id];
                txt.dataGroupId=id.split('#')[0];
                this.stage.addChild(txt);
            }

javascript js_spider和副本

js_spider and copy
[1]下面的2个文件的步骤和说明:
①文件1,先运行一遍,相当于注入外部js文件的作用
②在修改文件2中的cssselector和输出格式后,运行文件2。获得有结果的页面最下方的textarea。
③点击textarea旁边的copy,完成最终的复制。
(注:document.execCommand('copy'),不支持用js执行,(会返回"fail"),但支持点击的事件,(会返回"success")。)
[2]
文件1:
function selText() {
  console.clear();
  textarea_id = 'copy3'document.getElementById(textarea_id).select();
  try {
    if (document.execCommand('cut', false, null)) {
      //    if(document.execCommand('copy', false, null)){
      console.log('success') //success info
    } else {
      console.log('fail') //fail info
    }
  } catch(err) {
    console.log(err)
    //fail info
  }
}
selText();

文件2:
// have checkbox
var e1 = document.querySelectorAll('div.songList ol li') var e = []
for (var i = 0; i < e1.length; i++) {
  if (e1[i].querySelector('input').checked) {
    e.push(e1[i].querySelector('a'))
  }
}

// common
var str1 = ''
var textarea_id = 'copy3'
var input_id = 'copy4'

// code_b
var e = document.querySelectorAll('div#maincontent div h2')
for (var i = 0; i < e.length; i++) {
  // for (var i=0;i<55;i++){
  // document.write(e[i].href+'\t'+e[i].innerText+'<br>');
  // document.write(e[i].innerText+'\t'+e[i].href+'<br>')
  // document.write(e[i].innerText+'<br>');
  // console.log(e[i].innerText)
  // console.log(e[i].innerText+'\t'+e[i].href)
  console.clear();
  str1 = str1 + e[i].innerText + '\t' + e[i].href + '\n';
  // str1 = str1 + e[i].innerText+'\n';
  // copyTextToClipboard(e[i].innerText)
}
// code_e

function again1() {
  var body = document.getElementsByTagName('body')[0];

  var textarea1 = document.getElementById(textarea_id);
   var button1 = document.getElementById(input_id);
  if (textarea1) {
    body.removeChild(textarea1)
  }
  if (button1) {
    body.removeChild(button1)
  }

  var textarea1 = document.createElement("textarea");
  // textarea1.innerHTML = text; 
  textarea1.setAttribute('id', textarea_id);
  textarea1.setAttribute('cols', '90');
  textarea1.setAttribute('rows', '10');
  //
  var button1 = document.createElement("input");
  button1.setAttribute('id', input_id);
  button1.setAttribute('type', 'button');
  button1.setAttribute('onclick', 'selText()');
  button1.setAttribute('value', 'Copy');
  //
  body.appendChild(textarea1);
  body.appendChild(button1);
}
again1();

var textarea1 = document.getElementById(textarea_id); 
textarea1.innerHTML = str1; //此处不能用innerText,否则\n会被转换为<br>
console.clear();
console.log(e.length);

其他文件:
// String.prototype.srepeat = function(num=1){
//     return new Array(num+1).join(this);
// }

var e = document.querySelectorAll('div#maincontent div h2')
var tab_num = 1

for (var i = 0; i < e.length; i++) {
  // for (var i=0;i<55;i++){
  var tab_num = 1
  console.clear();
  str1 = str1 + e[i].innerText + '\t'.repeat(tab_num) + e[i].href + '\n';
  // str1 = str1 + e[i].innerText+'\n';
  // str1 = str1 + e[i].src+'\n';
  // console.log(e[i].innerText)
  // console.log(e[i].innerText+'\t'+e[i].href)
}

function spider2(){
var e1 = document.querySelectorAll("ul div [depth='1']")
for (var i1 of e1){
    var e2 = [];
    var tab_num = 1
    str1 = str1 + i1.querySelectorAll('a')[0]['href'] + '\t'.repeat(tab_num) + i1.querySelectorAll('a')[0].innerText + '\n'
    var e2 = i1.querySelectorAll("ul div [depth='2']")
    for (var i2 of e2){
        var e3 = [];
        str1 = str1 + i2.querySelectorAll('a')[0]['href']+ '\t'.repeat(tab_num + 1) + i2.querySelectorAll('a')[0].innerText + '\n'
        var e3 = i2.querySelectorAll("ul div [depth='3']")
        for (var i3 of e3){
        str1 = str1 + i3.querySelectorAll('a')[0]['href']+'\t'.srepeat(tab_num + 2) + i3.querySelectorAll('a')[0].innerText + '\n'
        }
    }
}
}

function again1(){
    var textarea_id = 'copy3'
    var input_id = 'copy4'
    var body = document.getElementsByTagName('body')[0];
 
    var textarea1 =document.getElementById(textarea_id)
    var button1 = document.getElementById(input_id)
    if (textarea1)
        {
        body.removeChild(textarea1)
        }
    if (button1)
        {
        body.removeChild(button1)
        }
    
    var textarea1 = document.createElement("textarea");     
    // textarea1.innerHTML = text; 
    textarea1.setAttribute('id',textarea_id);
    textarea1.setAttribute('cols','90');
    textarea1.setAttribute('rows','10');
    //
    var button1 = document.createElement("input");
    button1.setAttribute('id',input_id);
    button1.setAttribute('type','button');
    button1.setAttribute('onclick','selText()');
    button1.setAttribute('value','Copy');
    //
    body.insertBefore(button1,body.childNodes[0]); 
    body.insertBefore(textarea1,body.childNodes[0]); 
//     body.appendChild(textarea1); 
//     body.appendChild(button1); 
}

again1();
 
var str1 = '';
spider1();
var textarea1 = document.getElementById(textarea_id);
textarea1.innerHTML = str1;

javascript ParticlesJs

ParticlesJs

particles-demo.js
/**
 * htpps://github.com/VincentGarreau/particles.js
 */ 

particlesJS("particles-js", {
  "particles": {
    "number": {
      "value": 60,
      "density": {
        "enable": true,
        "value_area": 800
      }
    },
    "color": {
      "value": "#ffffff"
    },
    "shape": {
      "type": "circle",
      "stroke": {
        "width": 0,
        "color": "#000000"
      },
      "polygon": {
        "nb_sides": 5
      },
      "image": {
        "src": "img/github.svg",
        "width": 100,
        "height": 100
      }
    },
    "opacity": {
      "value": 0.1,
      "random": false,
      "anim": {
        "enable": false,
        "speed": 1,
        "opacity_min": 0.1,
        "sync": false
      }
    },
    "size": {
      "value": 6,
      "random": false,
      "anim": {
        "enable": false,
        "speed": 40,
        "size_min": 0.1,
        "sync": false
      }
    },
    "line_linked": {
      "enable": true,
      "distance": 150,
      "color": "#ffffff",
      "opacity": 0.1,
      "width": 2
    },
    "move": {
      "enable": true,
      "speed": 1.5,
      "direction": "top",
      "random": false,
      "straight": false,
      "out_mode": "out",
      "bounce": false,
      "attract": {
        "enable": false,
        "rotateX": 600,
        "rotateY": 1200
      }
    }
  },
  "interactivity": {
    "detect_on": "canvas",
    "events": {
      "onhover": {
        "enable": false,
        "mode": "repulse"
      },
      "onclick": {
        "enable": false,
        "mode": "push"
      },
      "resize": true
    },
    "modes": {
      "grab": {
        "distance": 400,
        "line_linked": {
          "opacity": 1
        }
      },
      "bubble": {
        "distance": 400,
        "size": 40,
        "duration": 2,
        "opacity": 8,
        "speed": 3
      },
      "repulse": {
        "distance": 200,
        "duration": 0.4
      },
      "push": {
        "particles_nb": 4
      },
      "remove": {
        "particles_nb": 2
      }
    }
  },
  "retina_detect": true
});

javascript 收件箱合同

inbox.sol
pragma solidity ^ 0.4.17;

contract Inbox {
    string public message;
    
    function Inbox(string initialMessage) public {
        message = initialMessage;
    }
    
    function setMessage(string newMessage) public {
        message = newMessage;
    }
    
 //   function getMessage() public view returns (string) { 
  //      return message;
  //  }
}