0

我有一个如下所述的选择列表:

<select id="edit-type" class="form-select ajax-processed valid" name="type">
   <option selected="selected" value="text">Text</option>
   <option value="select">Drop Down List</option>
   <option value="file">Single File Submission</option>
   <option value="license">License</option>
</select>

我想使用 jQuery 来找到这个 select 元素,但我想使用 name 属性来找到它(而不是 id 或 class 属性,因为它们可能会改变)。我尝试了以下方法,但它不起作用:

$(':select[name="type"]').live('change', function() {....

我是 JavaScript 新手,所以我想我在这里遗漏了一些基本的东西。我以为这会奏效。我不能:select[name="type"]用作选择器吗?

4

2 回答 2

0

我认为下面的代码可能会有所帮助:

您可以使用以下方法按名称查找元素:

   $('select[name="type"]').live('change', function() 

要获得选定的选项,您可以使用:

$('select[name="type"] option:selected').text();
$('select[name="type"] option:selected').val(
于 2013-06-14T21:13:52.677 回答
0

Remove : before the selector

$('select[name="type"]').live('change', function() {....

or

$(':input[name="type"]').live('change', function() {.... // if you have any other input with the same it will select that too. SO better to go with first option. 

Also make sure this is under $(document).ready(function(){...});

See:

Just to update about your question on :input

:input

from doc

The :input selector basically selects all form controls. Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

于 2013-06-14T20:52:59.363 回答