JavaScript development must master skills - better use of jQuery attr method

Keywords: Javascript Attribute JSON SQL JQuery

The previous several articles are all long speeches. It's really a bit hard to read them all at once. Today, I'd like to share a skill of using attr() in development. Maybe we haven't used it like this. It works with the template string module in the ES6 standard. Let's take a look at the template string and its use:

// Conventional JavaScript Language, the output template is usually written like this (used below jQuery Method).
$('#result').append(
  'There are <b>' + basket.count + '</b> ' +
  'items in your basket, ' +
  '<em>' + basket.onSale +
  '</em> are on sale!'
);

// The above writing method is rather cumbersome and inconvenient, ES6 Template string is introduced to solve this problem.
$('#result').append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);

Look at it like this. It's a lot simpler. Imagine that if the code is too long, you need to check whether the single quotation mark or plus sign is missing. Especially when we write sql statements, we understand all the sql statements, right! Let's look at:

let sql = "select id,create_by,user_name,c_name,c_value,is_off,remarks ," +
                "   date_format(create_time,'%Y-%m-%d %H:%i:%s') create_time" +
                " from app_shop_category a" +
                " LEFT JOIN common_user_info b on a.create_by = b.user_id";
            
let sql1 = ` select id,create_by,user_name,c_name,c_value,is_off,remarks,
                date_format(create_time,'%Y-%m-%d %H:%i:%s') create_time
             from app_shop_category a
             LEFT JOIN common_user_info b on a.create_by = b.user_id`;

About template strings can be found in ES6 standard Learn more

1, Definition and usage of attr()

The attr() method sets or returns the attributes and values of the selected element.

When this method is used to return an attribute value, the value of the first matching element is returned.

When this method is used to set attribute values, one or more attribute / value pairs are set for the matching element.

Two. Grammar

Return the value of the property:

$(selector).attr(attribute)

Set properties and values:

$(selector).attr(attribute,value)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Rookie tutorial(runoob.com)</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    console.log("The picture width is:",$("img").attr("width"))  // Picture width: 284
    $("button").click(function(){
        $("img").attr("width","500");
        console.log("Set the picture width to:",$("img").attr("width"))  // Set the picture width to 500
    });
});
</script>
</head>
<body>
<img src="img_pulpitrock.jpg" alt="Pulpit Rock" width="284" height="213">
<br>
<button>Set up for pictures width attribute</button>

</body>
</html>

Use the function to set properties and values:

$(selector).attr(attribute,function(index,currentvalue))
$(document).ready(function(){
    $("button").click(function(){
        $("img").attr("width",function(n,v){
            return v-50;
        });
    });
});

Set multiple properties and values:

$(selector).attr({attribute:value, attribute:value,...})
$(document).ready(function(){
    $("button").click(function(){
        $("img").attr({width:"150",height:"100"});
    });
});

 

3, attr() with ES6

Next, let's look at the use of attr() with ES6. The example is as follows:

Let's take a look at this first

"<a onclick='addVersion(" + id + "," + pid + ",\"" + pids + "\",\"" + name + "\",\""+source+"\");'>Newly added</a>";

If we need a lot of parameters, is this method unsafe.

OK, let's implement a simple paging list, and set the configuration operation link for the operation column of each record. In the a tag, we first obtain the json data of this section, and pass the json data through data param = "${json. Stringfy (row)}", and return the attribute value through $(obj). Attr ('data param ') in the method, then we can get the json put into data param. Just convert to json format data.

$('#configList').datagrid({
            url: '...',
            method: 'post',
            rownumbers: true,
            striped: true,
            fitColumns: true,
            border: false,
            fit: true,
            columns:[[
                {field:'user_no',title:'Account number',align:'center'},
                {field: "remark", title: "Remarks",  align: 'center'},
                {field: "operate",title: "operation",  align: "center",formatter:function (value,row,index) {
                        let config = `<a class="easyui-linkbutton" data-param='${JSON.stringify(row)}' onclick="configOperator(this)">To configure</a>`; 
            return
config;
          }}
        ]],
        onLoadSuccess:
function(json){ },
        onLoadError :
function (rowData, rowIndex) {
          $.messager.alert(
'Tips','Error loading data,Please try again later...');
        },
        pagination:
true,
        loadMsg:
"Loading, please wait........",
  });

// Configuration method
function configOperator(obj) {
  let param
= $(obj).attr('data-param');
  let params
= JSON.parse(param)
  console.log(params);
}

This is a more secure implementation of the parameter transfer process. I can imagine that it can also be used in many other scenes.

OK, that's all. Thank you for watching. If you like, please pay attention to me!

 

 

 

 

 

Posted by tomwerner on Tue, 14 Apr 2020 09:25:46 -0700