I have a button
element with a span
tag inside:
<button onClick={this.doSomething.bind(this)}>
<span>Some text</span>
</button>
The doSomething
function is as follows:
function doSomething(e){
e.stopPropagation();
e.preventDefault();
if(e.target.classList.contains("disabled")){
return false;
}
// Continue with button action...
}
When the button has the disabled
class I do not want the button to fire. Currently, when the rim of the button is clicked it does not fire. However, when the inner part of the button is clicked (where the text is) it fires - I want to avoid this - how do i do this?
I have a button
element with a span
tag inside:
<button onClick={this.doSomething.bind(this)}>
<span>Some text</span>
</button>
The doSomething
function is as follows:
function doSomething(e){
e.stopPropagation();
e.preventDefault();
if(e.target.classList.contains("disabled")){
return false;
}
// Continue with button action...
}
When the button has the disabled
class I do not want the button to fire. Currently, when the rim of the button is clicked it does not fire. However, when the inner part of the button is clicked (where the text is) it fires - I want to avoid this - how do i do this?
3 Answers
Reset to default 3I would suggest using disabled attribute of a button instead of a class. disabled attribute
Then you could still style button using:
.button[disabled] or button[disabled]
Hope this helps.
The reason is that the clicked element, the SPAN, is the event target
, rather than the BUTTON, which is the currentTarget. Check the class for the event.currentTarget
instead:
function doSomething(e){
e.stopPropagation();
e.preventDefault();
console.log('triggered', e.target, e.currentTarget);
if (e.currentTarget.classList.contains("disabled")) {
console.log('Exit');
return false;
}
console.log('Continue'); // Continue with button action...
}
button.disabled span {
pointer-events: none;
}
<button onclick="doSomething(event)" class="disabled">
<span>Some text</span>
</button>
You can handle it with CSS rule:
button.disabled span {
pointer-events: none;
}
Or even:
button.disabled * {
pointer-events: none;
}
function doSomething(e){
e.stopPropagation();
e.preventDefault();
if(e.target.classList.contains("disabled")){
return false;
}
console.log('triggered', e.target);
// Continue with button action...
}
button.disabled span {
pointer-events: none;
}
<button onclick="doSomething(event)" class="disabled">
<span>Some text (Disabled)</span>
</button>
<button onclick="doSomething(event)" class="">
<span>Some text</span>
</button>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744835136a4596216.html
评论列表(0条)