使用jQuery检测Android手机的a标签

huangapple go评论59阅读模式
英文:

Detect android phone via jQuery for a tag

问题

// 用内联的 JavaScript/jQuery 在 HTML 文档中实现以下逻辑:
// 如果是安卓手机点击“返回首页”按钮,链接为"x.com",否则链接为"z.com"

$('.android').on('click', function() {
    if (/Android/i.test(navigator.userAgent)) {
        // 是安卓手机
        $(this).attr('href', 'x.com');
    } else {
        // 不是安卓手机
        $(this).attr('href', 'z.com');
    }
});
英文:

I have this code in my html source

<body>
 <a class="android">back to home page</a>
</body>

how can i use inline js/jquery code to say if android phone click "back to home page" button href= "x.com" else href= "z.com"
I want to use inline source js/jquery in my html document

答案1

得分: 0

<a class="android" id="android" >回到首页</a>
let anchor = document.getElementById("android");
if (screen.width <= 640) { 
    anchor.href="链接"
 }
else{
    anchor.href="链接2"
}
英文:

You can use the following code in

<a class="android" id="android" >back to home page</a>

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let anchor = document.getElementById(&quot;android&quot;);
if (screen.width &lt;= 640) { 
    anchor.href=&quot;link&quot;
 }
else{
    anchor.href=&quot;link2&quot;
}

<!-- end snippet -->

答案2

得分: 0

&lt;body&gt;
  &lt;script type=&quot;text/javascript&quot;&gt;
    var isAndroid = / Android/i.test(navigator.userAgent.toLowerCase());

    if (isAndroid) {
      document.getElementById(&quot;abc&quot;).href = &quot;https://stackoverflow.com/&quot;;
    } else {
      document.getElementById(&quot;abc&quot;).href = &quot;https://link2&quot;;
    }
  &lt;/script&gt;
&lt;/body&gt;
英文:
&lt;body&gt;
  &lt;script type=&quot;text/javascript&quot;&gt;
    var isAndroid = / Android/i.test(navigator.userAgent.toLowerCase());
 
    if (isAndroid) {
      document.getElementById(&quot;abc&quot;).href = &quot;https://stackoverflow.com/;
    } else {
      document.getElementById(&quot;abc&quot;).href = &quot;https://link2&quot;;
    }
  &lt;/script&gt;
&lt;/body&gt;

huangapple
  • 本文由 发表于 2023年2月19日 18:51:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定