简体   繁体   中英

button OnClick event not firing

There is a page and I am trying to attach an onclick event to the button ("SEARCH CRUISES") on the page but the onclick event is not firing correctly. Here is my code:

<script>
debugger;
var x = document.getElementsByClassName("cdc-filters-search-cta")

for (i=0; i< x.length; i++){
    if(x[i].text.trim().indexOf("SEARCH") >= 0 &&  x[i].text.trim().indexOf("CRUISES") >= 0){
        x[i].onclick = function(){
            console.log("Search button clicked");           
        };
        break;
    }   
}   

Here is the complete html: https://jsfiddle.net/g0tkqrx6/

I have tried attaching the onclick event to the object in many different ways but I am not able to get the click event to fire. I would appreciate if anybody can provide some insight as to what I could be doing wrong here.

Thanks in advance

You must use textContent for element text and make it uppercase.

Here is an example:

 var x = document.getElementsByClassName("cdc-filters-search-cta") for (var i=0; i< x.length; i++){ var element = x[i] ; if((element.textContent ).toUpperCase().indexOf("SEARCH") >= 0 && element.textContent.toUpperCase().indexOf("CARS") >= 0){ element.onclick = function(){ console.log("Search button clicked"); }; break; } } 
 <button class="cdc-filters-search-cta"> SEARCH</button> <button class="cdc-filters-search-cta"> CARS</button> <button class="cdc-filters-search-cta">SEARCH CARS</button> 

Seeing your html would be helpful. Make sure you are interacting with the correct names for your js events.

Well to start with I think you should really take a look at this article on why you shouldn't add inline functions or css. https://www.tomdalling.com/blog/coding-styleconventions/why-inline-comments-are-generally-a-bad-idea/

Secondly I think your issue is that you are trying to add a click event to an angular front end which is controlled by the ngModel and also the site is probably compiled AOT. However you can try this,

  let x = document.querySelectorAll('.cdc-filters-search-cta'); let term = /[(SEARCH)(CRUISES)]/ x = Array.from(x); x.forEach(span => { if (term.test(span.textContent)) { return span.addEventListener('click', (e) => { console.log('span clicked') }); } }) 

I changed your code to querySelectorAll which returns an array and I used a forEach loop to add an eventListener. Not sure how well that will go down with your angular, but maybe.

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