javascript jQuery的使わずトグルクラス

toggle
<script>
						function toggle() {
                            const toggler = document.getElementById('js-toggle');
                            toggler.classList.toggle('is-open');
						}
					</script>

javascript javascriptメディアクエリで分岐

.js
$(function() {
    // 600px以上の場合
    if (window.matchMedia( '(min-width: 600px)' ).matches) {
      // 処理
    } else { // 600px以下の場合
      // 処理
    };
});

javascript Listar todos arquivos de uma pasta com o Node

index.js
async function listAllFilesInDir(dir, fileList = []) {
	const files = await fs.promises.readdir(dir);
	for (const file of files) {
		const stat = await fs.promises.stat(path.join(dir, file));
		if (stat.isDirectory()) {
			fileList = await listAllFilesInDir(path.join(dir, file), fileList);
		} else {
			fileList.push(path.join(dir, file));
		}
	}
	return fileList;
}

javascript 通用脚本注入

设置脚本以在head标签中注入javascript。 <br/> <br/> |变量|说明|示例| <br/> | ---------------------- | :----------------------:| ---------------------------------------:| <br/> | 'src'|文件的路径| 'google.com/api/gtm.js'| <br/> | 'id'|脚本标识符| 'gtm-container'| <br/> | 'VenderTrack'|供应商的名字| 'GoogleTagManager'|

gtm_insert_script.js
(function(a,b,c,d,e,f,g,h){
  if(typeof a['VendorTrack'] !== 'undefined') { return; }
  a['VendorTrack'] = e;
  g = b.getElementsByTagName(c)[0];
  f = b.createElement(c);
  f.type = 'text/javascript';
  f.async = true;
  f.src = '//' + d ;
  f.id = e;
  g.parentNode.insertBefore(f, g);
})(window,document,'script','src','id');

javascript 选择 。动态爱情,级联爱情

https://apex.oracle.com/pls/apex/f?p = 193000:603:17743481449330 :: NO ::: <br/> https://community.oracle.com/thread/3790387

js
function onChangeBrandGetShips(e){
	var selected_val = '';
  var brand = $(e.triggeringElement).parent().parent().find('select[name="f03"]').val();
  var set_list = $(e.triggeringElement).parent().parent().find('select[name="f04"]');
	var row_id = $(e.triggeringElement).parent().parent().find('input[name="f02"]').val();
  
  apex.server.process ( 
      "GET_SHIPS",
      {
         x01: brand,
				 x02: row_id
      },
      {
         success: function( pData ) {

         $(set_list).find('option').remove();

         $.each(pData, function(key, innerjson) {
         $(set_list).append($('<option>', {
         value: innerjson.VALUE,
         text: innerjson.NAME
         }));
         if (innerjson.SELECTED !== '') {selected_val = innerjson.SELECTED};
         });
				 
            // if found selected value
           if (selected_val !== '') {
           $(set_list).find('option')
             .each(function() 
               {
                 this.selected = (this.text == selected_val);
               }
             );
           }
         },
      }
   );

}
sql
DECLARE
	l_param            VARCHAR2 (40)   := apex_application.g_x01; 
	l_row_id           VARCHAR2 (40)   := apex_application.g_x02; 
	l_list             VARCHAR2 (4000) := '{"KEY0": {"NAME":"- Select -","VALUE":"","SELECTED":""},';
	l_selected_value	 varchar2 (200);
	v_count            NUMBER          := 1;
BEGIN 

	if l_row_id is not null then
		begin
			select ship
			  into l_selected_value
		  	from lgms_frt_plan_dd
		   where lgms_frt_plan_dd_id = l_row_id;
		exception when others then
			l_selected_value := null;
		end;
  end if;

   FOR c IN (select item_shtname
                  , item_code
               from lgms_lov_v
              where upper(lov_code) = 'SHIPS'
                and attribute3 = l_param -- 'PCL'
              order by 1)
   LOOP
      l_list :=
            l_list
         || '"KEY' || v_count
         || '":{"NAME":"' || c.item_shtname
         || '","VALUE":"' || c.item_code
         || '","SELECTED":"' || CASE WHEN c.item_code = l_selected_value
                                     THEN c.item_shtname
                                ELSE NULL
                                 END
         || '"},';
      v_count := v_count + 1;
   END LOOP;

   l_list := RTRIM (l_list, ',');
   l_list := l_list || '}';
   HTP.p (l_list);
END;
org
1. Dynamic Action on Change of jQuery Selector select[name="f03"] - runs on page load - is:

var elem = '#' + this.triggeringElement.id;
var key = '#' + 'f02_' + this.triggeringElement.id.substring(4);
var set_list = '#' + 'f04_' + this.triggeringElement.id.substring(4);


var key_val = $(key).val();
var elem_val = $(elem).val();

var selected_val = '';

apex.server.process ( 
    "getEmployees",
    {
      x01: elem_val,
      x02: key_val
    },
    {
      success: function( pData ) {

      $(set_list).find('option').remove();

      $.each(pData, function(key, innerjson) {
      $(set_list).append($('<option>', {
      value: innerjson.VALUE,
       text: innerjson.NAME
        }))
	  if (innerjson.SELECTED != '') {selected_val = innerjson.SELECTED};
      });

      if (selected_val != '') {
        $('select' + set_list + ' option').each(function() 
        {this.selected = (this.text == selected_val);});
      }
       },
    }
);
2. On Demand Process "getEmployees" - gets the employes of the selected department + selected values for an existing record:

DECLARE
   v_deptno           VARCHAR2 (40)   := TO_NUMBER (apex_application.g_x01);
   v_id               VARCHAR2 (40)   := TO_NUMBER (apex_application.g_x02);
   v_ename            VARCHAR2 (4000) := '{"KEY0": {"NAME":"- Select Employee -","VALUE":"","SELECTED":""},';
   v_selected_empno   VARCHAR2 (40);
   v_count            NUMBER          := 1;
BEGIN
   IF v_id IS NOT NULL
   THEN
      SELECT empno
        INTO v_selected_empno
        FROM emp_log
       WHERE ID = v_id;
   END IF;

   FOR c IN (SELECT ename, empno
               FROM emp
              WHERE deptno = v_deptno)
   LOOP
      v_ename :=
            v_ename
         || '"KEY'
         || v_count
         || '":{"NAME":"'
         || c.ename
         || '","VALUE":"'
         || c.empno
         || '","SELECTED":"'
         || CASE
               WHEN c.empno = v_selected_empno
                  THEN c.ename
               ELSE NULL
            END
         || '"},';
      v_count := v_count + 1;
   END LOOP;

   v_ename := RTRIM (v_ename, ',');
   v_ename := v_ename || '}';
   HTP.p (v_ename);
END;
3. Employee Select List Query is:

SELECT NULL d, NULL r
  FROM DUAL
 WHERE 1 = 2
4. Dynamic Action on Change of jQuery Selector select[name="f03"] - runs on change:

var elem = '#' + this.triggeringElement.id;
var key = '#' + 'f02_' + this.triggeringElement.id.substring(4);
var set_list = '#' + 'f04_' + this.triggeringElement.id.substring(4);


var key_val = $(key).val();
var elem_val = $(elem).val();

var selected_val = '';

apex.server.process ( 
    "getEmployees",
    {
      x01: elem_val,
      x02: key_val
    },
    {
      success: function( pData ) {

      $(set_list).find('option').remove();

      $.each(pData, function(key, innerjson) {
      $(set_list).append($('<option>', {
      value: innerjson.VALUE,
       text: innerjson.NAME
        }))
	  if (innerjson.SELECTED != '') {selected_val = innerjson.SELECTED};
      });

      if (selected_val != '') {
        $('select' + set_list + ' option').each(function() 
        {this.selected = (this.text == selected_val);});
      }
       },
    }
);

javascript 反应 - 钩子

反应 - 钩子

Counter.jsx
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
    <input 
      onChange={(e) => setCount(e.target.value)} 
      type="number" 
      value={count}>
    </input>
      <p>Le compteur est  à : {count} </p>
      <button onClick={() => setCount(Number(count) + 1)}>
        +1
      </button>
      <button onClick={() => setCount(Number(count) - 1)}>
        -1
      </button>
    </div>
  );
}

export default Counter;

javascript 以外のところをクリックされたら消す

script
//dropdownエリア外をクリックされたときに閉じる
  const closeDropdown = (el) => {
    if (el.target.closest('.dropdown')) {
      return false;
    }
    alert('on');
    dropdowns.forEach((el)=>{
      el.classList.remove('restoreDropdown')
    });
  };

javascript 表达式评估

simplify.js
function simplify(poly){
  let obj = {},ordered = {},expr = ''
  for(let i=0;i<poly.length;i++){
    let coeff='',canIterate = true,index = i,variable='',sign='+';
    while(canIterate){
      let val = poly[index]
      if(val ==="+" || val === '-') sign = val
      else if(!isNaN(parseInt(val))) coeff+=parseInt(val);
      else variable+=val;
      index++
      canIterate = poly[index] !== '-' && poly[index] !== '+' && index<poly.length ? true : false
    }
    // console.log(`${sign} ${coeff} ${variable}`)
    variable = variable.split('').sort().join('')
    if(coeff=='') coeff = 1
    coeff = parseInt(sign+coeff)
    if(!obj[variable]) obj[variable] = []
    obj[variable].push(coeff)
    i = index-1
  }

  let sorted = Object.keys(obj).sort((a,b)=>{
    return a<b ? -1 : 1
  })
  sorted = sorted.sort((a,b)=>{
    return a.length - b.length
  })
  sorted.forEach(key=>{
    ordered[key] = obj[key]
  })
  // console.log(sorted)
  Object.entries(ordered).forEach((entry,index)=>{
    let coeff = entry[1].reduce((a,b)=>a+b)
    if(!(coeff === 0)){
      if(coeff===-1) expr+= '-'+entry[0]
      else if(coeff<-1) expr+=coeff+entry[0]
      else if(coeff === 1 && index === 0) expr+=entry[0]
      else if(coeff===1 && index > 0) expr+='+'+entry[0]
      else if(coeff > 1 && index > 0) expr+='+'+coeff+entry[0]
      else expr+=coeff+entry[0]
    }
  })
  return expr
}

javascript asyncData()

这是在vue(paged)组件中使用asyncData的方法。

asyncData.js
////////////----------------------------------------------------------------------

// special property on the pages components (only) that nuxt will execute on the server
  // server waits for it to finish and then return it to the client (hence we will get a pre-rendered complete page back to the client)
  // this also replaces the data() as well as created() in the client side (this executes on the server)
  // we cant use normal data then which will override the asyncData & can get unwanted effect
  // inside of async ==> we get this.$route.params(params object holds all route parameters) by using context.params (or context.route.params)
  // we also know that this keyword can't be used here
  // for individual data we still always perform async because it might need some extra data
  // we can only use asyncData() inside of a paged component
  //async data will be executed on the server wehn we load it the first time or on client on subsiquent navigation & action
  // this is powerfull for page specific data

  //---------fetch vs asyncData
  //* async merge the data in data property, fetch stores the data on the store (using commit inside it)
  // better option than fetch is to use nuxtServerInit()
  asyncData(context) { //callback arg is not used, so nuxt does not wait that to be called
    // this keyword does not work as expected in async data coz async data runs before this component is created
    // we need to give asyncData the idea about when we are done (otherwise imediately returns the finished page
    // one solution is to return a promise ( thus it waits for the promise to be resolved and gives the result)
    // the syntax is return new Promise() which is to wrap the whole setTimeout
    // other one is to use callback (in aync data we get two arguments (context, callback)), execute callback when we are done
    // execution of callback method tells the async method that we are done
    // we use callback instead of return
    return new Promise(resolve => {
      setTimeout(() => {
        //if first arg is not null then it returns error autometically
        resolve({
          loadedPosts: [
            {
              id: "1",
              title: " First Post",
              previewText: "This is the first post",
              thumbnail:
                "https://images.pexels.com/photos/1509428/pexels-photo-1509428.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
            },
            {
              id: "2",
              title: " Second Post",
              previewText: "This is the second post",
              thumbnail:
                "https://images.pexels.com/photos/1509428/pexels-photo-1509428.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
            },
            {
              id: "3",
              title: " Third Post",
              previewText: "This is the third post",
              thumbnail:
                "https://images.pexels.com/photos/1509428/pexels-photo-1509428.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
            }
          ]
        });
      }, 1500);
      //once resolved then marge data with other component data (inside then)==>(map the data as needed using new obj or return the object as a whole)
      // catching errors inside of promise
      // then handles resolve , catch handles reject
    })
      .then(data => {
        console.log(data);
        return data;
      })
      .catch(e => console.log(new Error()));
  }
  
  
  
  //-------------CALLBACK PATTERN------------------------------
  
  //--------------Later version----------------------
  asyncData(context, callback) {
    //data must wait till it finish loading on the server before it is send to client (thus must use callback or promise)
    setTimeout(() => {
      callback(null, {
        loadedPost: {
          id: "1",
          title: " First Post (id " + context.params.id + ")",
          previewText: "This is the first post",
          author: "Muhtasim Musfiq",
          updatedDate: new Date(),
          content: "Dummy text, not the preview text",
          thumbnail:
            "https://images.pexels.com/photos/1509428/pexels-photo-1509428.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
        }
      });
    }, 1000);
  }
  
  
  
  //---------------------------async data using backend----------------
  asyncData(context) {
    //callback is not needed as we are using promise
    return axios
      .get(
        "https://nuxt-blog-e3c31.firebaseio.com/post/" +
          context.params.id +
          ".json"
      )
      .then(res => {
        //merging with component data (loadedData)
        return {
          loadedPost: res.data
        };
      })
      .catch(e => context.error(e));
    //id is fetched from route params (context.params.id === route.params.id)

javascript DOM至图像

使用dom-to-image将html dom直接更改为图像。

domToImage.js
      import domToImage from 'dom-to-image'
      const element = document.querySelector('.bg-c-dhtmlx-scheduler');
      domToImage.toJpeg(
        element,
        {
          quality: 0.95,
          bgcolor: '#fff',
        })
        .then( dataUrl => {
          const link = document.createElement('a');
          link.download = `${moment().format('YYYY-MM-DD')}-${dateMode}-schedulerFile.jpeg`;
          link.href = dataUrl;
          link.click();
        });