简体   繁体   中英

IS there a way to access data-binding in span tag and store it in a variable in the script tag? knockoutjs

oi

<table class="table table-striped table-sm small" >
<thead class="bg-dark text-light">
    <tr>
        <th scope="col">Id</th>
        <th scope="col">Name</th>
        <th scope="col">Nationality</th>
        <th scope="col" class="text-right"></th>
    </tr>
</thead>
<tbody data-bind="foreach: records">
    <tr>
        <td class="align-middle" data-bind="text:DriverId"></td>
        <td class="align-middle" data-bind="text:Name"></td>
        <td class="align-middle">  
            <span id = "nation" data-bind="text:Nationality" class="float-left"> </span>
            
            <img  id="flagicon" src="" alt="" class="flag float-right float-center" />
            <script>
                
                
                var alpha_2_code = "pt";
                
               /* for(let i=0; i < countrycodesobj.length ; i++){
                    if(countrycodes[i].Nationality === (data-bind = "text:Nationality"))
                        alpha_2_code = countrycodes[i].alpha_2_code;
                }*/
                
                var myPath = "https://countryflagsapi.com/png/" + alpha_2_code;
                document.getElementById("flagicon").src= myPath;
            </script>

        </td>
       
    </tr>
</tbody>

I want the information > data-bind="text:Nationality" < stored in a variable in script tag. Im getting the information from an api and its being handled by knockoutjs. My knockoutjs knowledge is scarce and i dont know if i can access the information data-bind="text:Nationality" in the script tags. Any solution whether in jquery, knockouts or javascript would be perfect. Thanks in advance.

you could make use of a simple function that you define before you applyBindings with knockout and after your countrycodesobj is defined, sth like:

function getFlagByNationality(n) {
    var alpha_2_code = "pt";
                
    for(let i=0; i < countrycodesobj.length ; i++){
      if(countrycodes[i].Nationality == n ){
         alpha_2_code = countrycodes[i].alpha_2_code;
      }
    }
    return "https://countryflagsapi.com/png/"+alpha_2_code;
}

you can then use this in data-bind attribute:

<img src="" data-bind="attr:{src: getFlagByNationality(Nationality)}"  />

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