Onclick bind event button

In HTML, I have a list of buttons. If the user presses the button, the
function will be called doCommand. The following code

<ul>
<li class="button1" onclick="doCommand('bold');" id="bold-button" title="bold">B</li>
<li class="button2" onclick="doCommand('bold');" id="italic-button" title="bold">I</li>
<li class="button3" onclick="doCommand('bold');" id="underline-button" title="bold">U</li>
<li class="button4" onclick="doCommand('bold');" id="strikethrough-button" title="bold">S</li>
</ul>

This is a simple expression, a normal web programmer will be encoded in this way. But I want to hide the event onclickand its function for security reasons. So the HTML will be like this

<ul>
<li class="button1" id="bold-button" title="bold">B</li>
<li class="button2" id="italic-button" title="bold">I</li>
<li class="button3" id="underline-button" title="bold">U</li>
<li class="button4" id="strikethrough-button" title="bold">S</li>
</ul>

Is there an effective way to do this? Hide the property onclick, but do the same work. I am using jQuery.

+3
source share
4 answers

if you set the same class for btns you can easily do:

Markup:

<ul>
<li class="button1 clickable" id="bold-button" title="bold">B</li>
<li class="button2 clickable" id="italic-button" title="bold">I</li>
<li class="button3 clickable" id="underline-button" title="bold">U</li>
<li class="button4 clickable" id="strikethrough-button" title="bold">S</li>
</ul>

JS:

$('.clickable').click(function(){/* doCommand('bold') or whatever */})

. , , , ( , , jQuery $). , ..

$('.clickable').click(function(){$(this).css('font-weight','bold')})
+5

, :

<li class="button button1"...
<li class="button button2"...

javascript.

$("li.button").click(function() {
  doCommand('bold');
});
+5

You can use the jquery document ready event to hook events:


$(function()
{
    $("#bold-button").click(function(){doCommand('bold');});
}
);
+1
source

Without changing the layout and using vanilla JS, you can do it as follows.

const list = document.querySelector('ul');

list.addEventListener('click', e => {
  if (e.target.classList.contains('button1')) {
    console.log('bold');
  };
  if (e.target.classList.contains('button2')) {
    console.log('italics');
  };
  if (e.target.classList.contains('button3')) {
    console.log('underline');
  };
  if (e.target.classList.contains('button4')) {
    console.log('strikethrough');
  };

})
<ul>
  <li class="button1" id="bold-button" title="bold">B</li>
  <li class="button2" id="italic-button" title="bold">I</li>
  <li class="button3" id="underline-button" title="bold">U</li>
  <li class="button4" id="strikethrough-button" title="bold">S</li>
</ul>
Run codeHide result

I assign an event to the parent list and check the class of the object, which allows you to perform any action.

+1
source

Source: https://habr.com/ru/post/1790712/


All Articles