简体   繁体   English

有没有办法访问 span 标签中的数据绑定并将其存储在脚本标签中的变量中? 淘汰赛

[英]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.我想要信息 > data-bind="text:Nationality" < 存储在脚本标签的变量中。 Im getting the information from an api and its being handled by knockoutjs.我从 api 获取信息并由 knockoutjs 处理。 My knockoutjs knowledge is scarce and i dont know if i can access the information data-bind="text:Nationality" in the script tags.我的 knockoutjs 知识匮乏,我不知道我是否可以访问脚本标签中的信息 data-bind="text:Nationality"。 Any solution whether in jquery, knockouts or javascript would be perfect.无论是 jquery、敲除还是 javascript,任何解决方案都是完美的。 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 ,它是您在 applyBindings with knockout 之前和 countrycodesobj 定义之后定义的,例如:

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)}"  />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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