dongnuo6310 2015-09-03 00:04
浏览 21
已采纳

把变量int选项选中

I'm trying to select an Select Option throuh jQuery with a PHP variable.

HTML

<div id="dom-target">
<?php 
    $output = $user->distritos;
    echo htmlspecialchars($output);
?>
</div>

jQuery

<script type="text/javascript">  
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
    jQuery('select[name="country"]').find('option:contains(" + myData + ")').attr("selected",true);    
</script>

But won't change, only if I replace option:contains(" + myData + ") by text, for example option:contains("123") it will select option with text "123"

What I'm doing wrong?

Thanks!

  • 写回答

1条回答 默认 最新

  • doumeng9188 2015-09-03 00:36
    关注

    You are concatenating a string inside of find(). Consider these three parts of the string:

    1. option:contains("
    2. the value of myData
    3. ")

    To build such a string, you'll need to close the single quote after the first part, append myData, and open the single quote again for the third part.

    Otherwise, you're selecting an <option> that contains the string " + myData + ".

    var $div = jQuery("#dom-target"),
        myData = $div.text();
    
    jQuery('select').find('option:contains("' + myData + '")').prop("selected", true);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="dom-target">foo</div>
    
    <select>
      <option>test</option>
      <option>option 2</option>
      <option>foo</option>
      <option>bar</option>
    </select>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度