简体   繁体   中英

How to disable a dynamically created <li> element?

i have created <ul> containing three <li> .i want to make disable one of my <li> on certain condition and insert some text in other <li> but failed.!

code

var d = document.createElement('div');
    d.className = "dataTables_paginate paging_bootstrap pagination";
    var UL = document.createElement('ul');
    var L1 = document.createElement('li');
    L1.className = 'prev';
    var A1 = document.createElement('a');
    A1.appendChild(document.createTextNode('← Previous'));
    A1.id = 'B1';
    L1.appendChild(A1);
    UL.appendChild(L1);
    var L3 = document.createElement('li');
    L3.className = 'active';
    var A3 = document.createElement('a');
    A3.appendChild(document.createTextNode('1'));
    L3.appendChild(A3);
    UL.appendChild(L3);
    d.appendChild(UL);
    var L2 = document.createElement('li');
    L2.className = 'next';
    var A2 = document.createElement('a');
    A2.appendChild(document.createTextNode('Next →'));
    L2.appendChild(A2);
    A2.id = 'B2';
    UL.appendChild(L2);
   var root = document.getElementById('rose');
   root.appendChild(d);

i want to B1 disable. i have tried following code:

script

  $('#B1').attr("disabled", true);

try with .off() :

$('#B1').off("click");

FYI:

Only form input elems are having property to get disabled, whether that is type text , select checkbox buttons etc.

While there is no disabled state for a li element, you can simulate the desired behavior like this:

$('#B1').css("color","gray").css("text-decoration","none");

Which will make it appear as if disabled (it will not be underlined and will appear grayed-out).

If in addition you need to disable the event listeners attached to it, you will have to use off() :

$('#B1').off("click");

Furthermore, if the element is a link, you will have to prevent it from being clickable, in the following way:

$('#B1').click(function() {
    $(this).preventDefault();  // prevent the default action
    $(this).stopPropagation(); // prevent event from bubbling up
    return false;              // just to be sure
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM