Hướng dẫn setattribute onclick javascript

This is an amazing function for cross-browser compatible event binding.

Got it from //js.isite.net.au/snippets/addevent

With it you can just do Events.addEvent[element, event, function]; and be worry free!

For example: [//jsfiddle.net/Zxeka/]

function hello[] {
    alert['Hello'];
}

var button = document.createElement['input'];
button.value = "Hello";
button.type = "button";

Events.addEvent[input_0, "click", hello];

document.body.appendChild[button];

Here's the function:

// We create a function which is called immediately,
// returning the actual function object.  This allows us to
// work in a separate scope and only return the functions
// we require.
var Events = [function[] {

  // For DOM2-compliant browsers.
  function addEventW3C[el, ev, f] {
    // Since IE only supports bubbling, for
    // compatibility we can't use capturing here.
    return el.addEventListener[ev, f, false];
  }

  function removeEventW3C[el, ev, f] {
    el.removeEventListener[ev, f, false];
  }

  // The function as required by IE.
  function addEventIE[el, ev, f] {
    // This is to work around a bug in IE whereby the
    // current element doesn't get passed as context.
    // We pass it via closure instead and set it as the
    // context using call[].
    // This needs to be stored for removeEvent[].
    // We also store the original wrapped function as a
    // property, _w.
    [[el._evts = el._evts || []][el._evts.length]
        = function[e] { return f.call[el, e]; }]._w = f;

    // We prepend "on" to the event name.
    return el.attachEvent["on" + ev,
        el._evts[el._evts.length - 1]];
  }

  function removeEventIE[el, ev, f] {
    for [var evts = el._evts || [], i = evts.length; i--; ]
      if [evts[i]._w === f]
        el.detachEvent["on" + ev, evts.splice[i, 1][0]];
  }

  // A handler to call all events we've registered
  // on an element for legacy browsers.
  function addEventLegacyHandler[e] {
    var evts = this._evts[e.type];
    for [var i = 0; i < evts.length; ++i]
      if [!evts[i].call[this, e || event]]
        return false;
  }

  // For older browsers.  We basically reimplement
  // attachEvent[].
  function addEventLegacy[el, ev, f] {
    if [!el._evts]
      el._evts = {};

    if [!el._evts[ev]]
      el._evts[ev] = [];

    el._evts[ev].push[f];

    return true;
  }

  function removeEventLegacy[el, ev, f] {
    // Loop through the handlers for this event type
    // and remove them if they match f.
    for [var evts = el._evts[ev] || [], i = evts.length; i--; ]
      if [evts[i] === f]
        evts.splice[i, 1];
  }

  // Select the appropriate functions based on what's
  // available on the window object and return them.
  return window.addEventListener
      ? {addEvent: addEventW3C, removeEvent: removeEventW3C}
      : window.attachEvent
          ? {addEvent: addEventIE, removeEvent: removeEventIE}
          : {addEvent: addEventLegacy, removeEvent: removeEventLegacy};
}][];

If you don't want to use such a big function, this should work for almost all browsers, including IE:

if [el.addEventListener] { 
    el.addEventListener['click', function, false]; 
} else if [el.attachEvent] { 
    el.attachEvent[' title', function]; 
} 

In response to Craig's question. You're going to have to make a new element and copy over the attributes of the old element. This function should do the job: [source]

function changeInputType[oldObject, oType] {
  var newObject = document.createElement['input'];
  newObject.type = oType;
  if[oldObject.size] newObject.size = oldObject.size;
  if[oldObject.value] newObject.value = oldObject.value;
  if[oldObject.name] newObject.name = oldObject.name;
  if[oldObject.id] newObject.id = oldObject.id;
  if[oldObject.className] newObject.className = oldObject.className;
  oldObject.parentNode.replaceChild[newObject,oldObject];
  return newObject;
}

Nội dung chính

  • setAttribute trong JavaScript và cách thiết lập giá trị thuộc tính của Element
  • Thiết lập giá trị thuộc tính của Element bằng cách tham chiếu trực tiếp
  • Tổng kết

Hướng dẫn cách sử dụng setAttribute trong JavaScript. Bạn sẽ biết cách sử dụng phương thức setAttribute để thiết lập giá trị thuộc tính của Element sau bài học này.

setAttribute trong JavaScript và cách thiết lập giá trị thuộc tính của Element

Cú pháp

setAttribute trong JavaScript là một phương thức của Element Object, có tác dụng thiết lập giá trị thuộc tính chỉ định của một Element. Nếu giá trị thuộc tính đã tồn tại thì nó sẽ được cập nhật, và nếu nó chưa tồn tại trước đó, thuộc tính mới kèm với giá trị của nó sẽ được thiết lập cho Element.

Cú pháp sử dụng thuộc tính setAttribute trong JavaScript để thiết lập thuộc tính chỉ định của Element như sau:

element.setAttribute[attributeName, value]

Trong đó

  • element là Element cần thiết lập thuộc tính
  • attributeName là tên thuộc tính cần thiết lập từ element
  • value là giá trị cần thiết lập của thuộc tính

Ví dụ cụ thể, chúng ta thêm thuộc tính class với giá trị bằng box vào Element ban đầu như sau:

let element = document.getElementById['shopname'];
element.setAttribute['class', 'box'];

Hoặc chúng ta có thể thay đổi giá trị thuộc tính id của nó thành place như sau:

let element = document.getElementById['shopname'];
element.setAttribute['id', 'place'];

Mã mẫu

Hãy cùng xem cách dùng setAttribute để thiết lập giá trị thuộc tính chỉ định của Element trong mã HTML như dưới đây:





Ví dụ minh hoạ cách dùng getAttribute



Kế hoạch mua sắm


Website
Shop mẹ và bé


Thiết lập thuộc tính của Element


function getElements[]{
let element = document.getElementById['box'];
element.children[0].setAttribute['target', '_blank'];
element.children[1].setAttribute['class', 'address'];
}



Trong mã HTML ở trên, sau khi click vào nút thì Element có thuộc tính id="box" sẽ được lấy thông qua phương thức getElementById. Sau đó bằng cách dùng phương thức setAttribute, chúng ta đã thay đổi cũng như thêm các thuộc tính vào trong các Element con của Element trên. Và kết quả:

.
  • Xem thêm: getElementById trong JavaScript

Thiết lập giá trị thuộc tính của Element bằng cách tham chiếu trực tiếp

Cú pháp

Ngoài cách dùng phương thức setAttribute mà Kiyoshi đã hướng dẫn ở trên, chúng ta còn có một phương pháp khác để thiết lập giá trị thuộc tính của Element, đó chính là cách tham chiếu trực tiếp tới thuộc tính và thay đổi thuộc tính đó.

Cú pháp thiết lập giá trị thuộc tính của Element bằng phương pháp này như sau:

element.name = 'value'

Trong đó

  • element là Element cần thiết lập thuộc tính
  • name là tên thuộc tính cần thiết lập từ element
  • value là giá trị cần thiết lập của thuộc tính

Tương tự như setAttribute thì nếu giá trị thuộc tính đã tồn tại thì nó sẽ được cập nhật, và nếu nó chưa tồn tại trước đó, thuộc tính mới kèm với giá trị của nó sẽ được thiết lập cho Element.

Ví dụ cụ thể, chúng ta thêm thuộc tính class với giá trị bằng box vào Element ban đầu như sau:

let element = document.getElementById['shopname'];
element.className = 'box';

Hoặc chúng ta có thể thay đổi giá trị thuộc tính id của nó thành place như sau:

let element = document.getElementById['place'];
element.id = 'box';

Khác với phương thức setAttribute thì tên thuộc tính được sử dụng trong phương pháp tham chiếu có thể giống hoặc khác với chính nó.

Các tên thuộc tính có thể sử dụng được quyết định theo mỗi loại tagname, có những tên thuộc tính có thể sử dụng cho tất cả các loại tagname, cũng có những tên thuộc tính chỉ có thể sử dụng cho một số tagname đặc định.

Ví dụ, thuộc tính href hoặc target của tagname

Bài viết liên quan

Hãy chia sẻ và cùng lan tỏa kiến thức lập trình Nhật Bản tại Việt Nam!

HOME>> học javascript - lập trình javascript cơ bản>>13. dom trong javascript

Bài sau
attributes trong JavaScript và cách lấy danh sách thuộc tính của Element
Bài tiếp
Thay đổi CSS bằng JavaScript
  • Bài viết mới nhất
  • Tách chuỗi trong PHP [explode, preg_split] tháng 9 17, 2022
  • Cắt chuỗi trong PHP [substr, mb_substr] tháng 9 17, 2022
  • Tách chuỗi thành mảng trong PHP [explode] tháng 9 17, 2022
  • Tìm kiếm chuỗi trong PHP [strpos] tháng 9 17, 2022
  • Đếm số lần xuất hiện của ký tự và chuỗi trong chuỗi PHP [substr_count] tháng 9 17, 2022
  • Chuyển chuỗi thành mảng trong PHP [str_split, mb_str_split] tháng 9 17, 2022
  • Tách từng ký tự trong chuỗi PHP [substr, preg_split] tháng 9 17, 2022
  • Xóa ký tự trong chuỗi PHP tháng 9 15, 2022
Profile

Tác giả : Kiyoshi [Chis Thanh]

Kiyoshi là một cựu du học sinh tại Nhật Bản. Sau khi tốt nghiệp đại học Toyama năm 2017, Kiyoshi hiện đang làm BrSE tại Tokyo, Nhật Bản.

Chủ Đề