我在JavaScript中有一个变量如下:
var testVariable="<input type='radio' name='gender' value='male' checked> Male<br><input type='radio' name='gender' value='female'>Female<br>"
现在我想获得具有 checked
属性的单选按钮的值。
我们如何实现这一目标?
答案 0 :(得分:6)
您可以将字符串解析为HTML
var testVariable = "<input type='radio' name='gender' value='male' checked> Male<br><input type='radio' name='gender' value='female'>Female<br>";
var parser = new DOMParser();
var doc = parser.parseFromString(testVariable, "text/html");
var val = doc.querySelector('input[type="radio"][checked]').value;
console.log(val)
答案 1 :(得分:3)
您可以将字符串填充到某个元素innerHTML
中,然后通常对其执行DOM选择:
const div = document.createElement('div');
div.innerHTML = testVariable;
const checkedInput = div.querySelector('input[type="radio"][checked]');
console.log(checkedInput.value);
请注意,您应确保将HTML字符串插入DOM中是安全的。恶意<script>
,<style>
和<object>
元素(仅举几例)可能会破坏您网页上的破坏。
答案 2 :(得分:0)
试试这个
public class MyBottomSheetBehavior<T extends View> extends android.support.design.widget.BottomSheetBehavior<T> {
private boolean mDependsOnBottomBar = true;
public MyBottomSheetBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, T child, View dependency) {
return (dependency instanceof BottomBar) || super.layoutDependsOn(parent, child, dependency);
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, T child, View dependency) {
if (dependency instanceof BottomBar) {
BottomBar bottomBar = (BottomBar) dependency;
if (mDependsOnBottomBar) {
//TODO this 4dp margin is actual shadow layout height, which is 4 dp in bottomBar library ver. 2.0.2
float transitionY = bottomBar.getTranslationY() - bottomBar.getHeight()
+ (getState() != STATE_EXPANDED ? Utils.dpToPixel(ContextProvider.getContext(), 4L) : 0F);
child.setTranslationY(Math.min(transitionY, 0F));
}
if (bottomBar.getTranslationY() >= bottomBar.getHeight()) {
mDependsOnBottomBar = false;
bottomBar.setVisibility(View.GONE);
}
if (getState() != STATE_EXPANDED) {
mDependsOnBottomBar = true;
bottomBar.setVisibility(View.VISIBLE);
}
return false;
}
return super.onDependentViewChanged(parent, child, dependency);
}
}